leetcode 389. Find the Difference

迈不过友情╰ 2023-07-12 05:04 95阅读 0赞

目录

一、问题描述

二、代码实现

1、桶排序

2、异或法

3、求和法


https://leetcode.com/problems/find-the-difference/

给定两个字符串,其中一个字符串是在另一个字符串的任意位置添加一个字母得到的,求这个字母

一、问题描述

测试用例:

  1. Example:
  2. Input:
  3. s = "abcd"
  4. t = "abcde"
  5. Output:
  6. e
  7. Explanation:
  8. 'e' is the letter that was added.

字符串的元素均为小写字母

二、代码实现

1、桶排序

  1. class Solution {
  2. //数组
  3. public char findTheDifference2(String s, String t) {
  4. int[] count = new int[26]; //HashMap, Array, Bits
  5. for (int i=0; i<s.length(); i++) {
  6. count[s.charAt(i) - 'a'] ++;
  7. }
  8. for (int i=0; i<t.length(); i++) {
  9. count[t.charAt(i) - 'a'] --;
  10. if (count[t.charAt(i)-'a'] == -1) {
  11. return t.charAt(i);
  12. }
  13. }
  14. return ' ';
  15. }
  16. //HashMap
  17. public char findTheDifference1(String s, String t) {
  18. HashMap<Character, Integer> map = new HashMap<>();
  19. for (int i=0; i<s.length(); i++) {
  20. char ch = s.charAt(i);
  21. map.put(ch, map.getOrDefault(ch, 0)+1);
  22. }
  23. for (int i=0; i<t.length(); i++) {
  24. char ch = t.charAt(i);
  25. if (!map.containsKey(ch)) {
  26. return ch;
  27. } else {
  28. if (map.get(ch) == 1) {
  29. map.remove(ch);
  30. } else {
  31. map.put(ch, map.get(ch)-1);
  32. }
  33. }
  34. }
  35. return ' ';
  36. }
  37. }

2、异或法

  1. class Solution {
  2. public char findTheDifference3(String s, String t) {
  3. char ret = t.charAt(t.length()-1);
  4. for (int i=0; i<s.length(); i++) {
  5. ret ^= s.charAt(i) ^ t.charAt(i); //c ^= s.chartAt(i); 等同于 c = (char)((int)c ^ (int)s.charAt(i));
  6. }
  7. return ret;
  8. }
  9. }

3、求和法

  1. class Solution {
  2. public char findTheDifference4(String s, String t) {
  3. int sum = t.charAt(t.length()-1);
  4. for (int i=0; i<s.length(); i++) {
  5. sum = (sum - s.charAt(i) + t.charAt(i));
  6. }
  7. return (char)sum;
  8. }
  9. }

参考:

https://leetcode.com/problems/find-the-difference/discuss/86850/Simple-JAVA-8ms-solution-4-lines

https://leetcode.com/problems/find-the-difference/discuss/86913/JavaC%2B%2B-1-liner

https://leetcode.com/problems/find-the-difference/discuss/87049/Simple-Java-Solution-Bit-Manipulation-5ms

https://leetcode.com/problems/find-the-difference/discuss/87095/Two-Java-Solutions-using-XOR-Sum

https://leetcode.com/problems/find-the-difference/discuss/86825/Java-solution-using-bit-manipulation

https://leetcode.com/problems/find-the-difference/discuss/87114/simple-cpp-solution

https://leetcode.com/problems/find-the-difference/discuss/86844/Java-Solution-using-array%3A-6ms

https://leetcode.com/problems/find-the-difference/discuss/87051/easy-Java-O(n)-solution-using-map

发表评论

表情:
评论列表 (有 0 条评论,95人围观)

还没有评论,来说两句吧...

相关阅读