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:
e

Explanation:
'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     }

 

 

 
posted @ 2016-08-31 22:18  琴影  阅读(1303)  评论(0编辑  收藏  举报