题目:
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.
代码:
自己的:
class Solution {
public:
char findTheDifference(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
auto r = mismatch(s.begin(), s.end(), t.begin());
return (*r.second);
}
};
别人的(1):
class Solution {
public:
char findTheDifference(string s, string t) {
// Similar to single number. Can do using hashmap...
int charmap[26] = {0};
for(char c: t) {
charmap[c-'a']++;
}
// Iterate over s, one letter will have count 1 left
for(char c: s) {
charmap[c-'a']--;
}
for(int i=0;i<26;i++) {
if (charmap[i] == 1)
return 'a'+i;
}
return -1;
}
};
别人的(2):
class Solution {
public:
char findTheDifference(string s, string t) {
char res = 0;
for(auto c: s)
res^=c;
for(auto c: t)
res^=c;
return res;
}
};
找出字符串中新增的字符
本文探讨了在两个字符串中找到被添加的额外字符的方法。通过对比和匹配,介绍了三种不同的算法实现,包括排序比较、哈希映射计数和位操作异或,展示了在不同场景下选择合适算法的重要性。
674

被折叠的 条评论
为什么被折叠?



