Leetcode - Find the Difference

My code:

public class Solution {
    public char findTheDifference(String s, String t) {
        char[] c1 = s.toCharArray();
        char[] c2 = t.toCharArray();
        Arrays.sort(c1);
        Arrays.sort(c2);
        int p1 = 0;
        int p2 = 0;
        while (p1 < c1.length) {
            if (c1[p1] != c2[p2]) {
                return c2[p2];
            }
            else {
                p1++;
                p2++;
            }
        }
        return c2[p2];
    }
}

自己写了两种方法。上面一种是 sort
time complexity: O(n log n)
space complexity: O(1)

下面的是用 hashtable

My code:

public class Solution {
    public char findTheDifference(String s, String t) {
        HashMap map = new HashMap();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (!map.containsKey(c)) {
                map.put(c, 1);
            }
            else {
                map.put(c, map.get(c) + 1);
            }
        }
        
        for (int i = 0; i < t.length(); i++) {
            char c = t.charAt(i);
            if (!map.containsKey(c)) {
                return c;
            }
            else {
                int times = map.get(c);
                times--;
                if (times == 0) {
                    map.remove(c);
                }
                else {
                    map.put(c, times);
                }
            }
        }
        return ' ';
    }
}

time complexity: O(n)
space complexity: O(n)

然后看了答案,有 Bit manipulation 的做法。竟然忘记可以拿异或来找 difference 了。

My code:

public class Solution {
    public char findTheDifference(String s, String t) {
        char c = 0;
        for (int i = 0; i < s.length(); i++) {
            c ^= s.charAt(i);
            c ^= t.charAt(i);
        }
        c ^= t.charAt(t.length() - 1);
        return c;
    }
}

reference:
https://discuss.leetcode.com/topic/55912/java-solution-using-bit-manipulation/2

Anyway, Good luck, Richardo! -- 09/22/2016

你可能感兴趣的:(Leetcode - Find the Difference)