LeetCode: 389 Find the Difference(easy)

题目:

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.

代码:

自己的:

1 class Solution {
2 public:
3     char findTheDifference(string s, string t) {
4         sort(s.begin(), s.end());
5         sort(t.begin(), t.end());
6         auto r = mismatch(s.begin(), s.end(), t.begin());
7         return (*r.second);
8     }
9 };

别人的(1):

 1 class Solution {
 2 public:
 3     char findTheDifference(string s, string t) {
 4         // Similar to single number. Can do using hashmap...
 5         int charmap[26] = {0};
 6         for(char c: t) {
 7             charmap[c-'a']++;
 8         }
 9         // Iterate over s, one letter will have count 1 left
10         for(char c: s) {
11             charmap[c-'a']--;
12         }
13         for(int i=0;i<26;i++) {
14             if (charmap[i] == 1)
15                 return 'a'+i;
16         }
17         return -1;
18     }
19 };

别人的(2):

 1 class Solution {
 2 public:
 3     char findTheDifference(string s, string t) {
 4         char res = 0;
 5         for(auto c: s) 
 6             res^=c;
 7         for(auto c: t) 
 8             res^=c;
 9         return res;
10     }
11 };

 

posted on 2017-09-05 11:14  玲珑子  阅读(135)  评论(0编辑  收藏  举报

导航