首页 > 代码库 > Leetcode 389 Find the Difference

Leetcode 389 Find the Difference

Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

Example:

Input:s = "abcd"t = "abcde"Output:eExplanation:‘e‘ is the letter that was added.

题目大意:

给定两个字符串s和t,都只包含小写字母。

字符串t由字符串s打乱顺序并且额外在随机位置添加一个字母组成。

寻找t中新增的那个字母。

测试用例如题目描述。

方法一:利用Hash表,
 1 char findTheDifference(string s, string t) { 2         int a[26] = {0}, lens = s.length(), lent = t.length(), i; 3         for(i = 0; i < lens; i++) 4             a[s[i] - a]++; 5         for(i = 0; i < lent; i++) 6             if(a[t[i] - a] <= 0) 7                 break; 8             else 9                 a[t[i] - a]--;10         return t[i];11     }

方法二:两个字符串加起来只有一个字符时单独的。。利用异或运算

1 char findTheDifference(string s, string t) {2         int ans = 0, i, lens = s.length(), lent = t.length();3         for(i = 0; i < lens; i++)4             ans ^= (s[i] - a);5         for(i = 0; i < lent; i++)6             ans ^= (t[i] - a);7         return a + ans;8     }

 

 

 

Leetcode 389 Find the Difference