Leetcode No.389 找不同

题目大意

给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例

输入:
s = "abcd"
t = "abcde"
输出:
e
解释:
'e' 是那个被添加的字母。

方法一:数组计数

可以用HashMap或者int数组存储每个字符出现的次数。

 public char findTheDifference(String s, String t) {
         int[] cnt = new int[26];
         for(int i=0;i

运行时间3ms,击败64.87%。

方法三:异或

两个相同字符异或的结果为0。

 public char findTheDifference(String s, String t) {
        int res = 0;
        for(Character temp:s.toCharArray())
            res ^= temp;
        for(Character temp:t.toCharArray())
            res ^= temp;
        return (char)res;
    }

方法三:int和差值

public char findTheDifference(String s, String t) {
        char[] arr1 = s.toCharArray();
        char[] arr2 = t.toCharArray();
        int res = 0;
        for(char temp:arr2)
            res+=(int) temp;
        for(char temp:arr1)
            res -= (int) temp;
        return (char)res;
    }

运行时间1ms,击败100%。

你可能感兴趣的:(Leetcode No.389 找不同)