给定两个字符串 s 和 t ,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例 1:
输入:s = "abcd", t = "abcde" 输出:"e" 解释:'e' 是那个被添加的字母。
示例 2:
输入:s = "", t = "y" 输出:"y"
提示:
0 <= s.length <= 1000t.length == s.length + 1s和t只包含小写字母
最开始没看清楚 length 的条件,看到随机重排想当然就直接用 unordered_sets 了
class Solution {
public:
char findTheDifference(string s, string t) {
unordered_set<char> st;
for(int i=0;i<s.size();i++){
st.insert(s[i]);
}
for(int i=0;i<t.size();i++){
auto it = st.find(t[i]);
if(it == st.end())return t[i];
}
}
};后来发现不对,这可以是重复的字母……
那就想到计数法,每碰到一个字母就计上去,最后一减,多出来的就是加上去的。
class Solution {
public:
char findTheDifference(string s, string t) {
vector<int> cnt(26,0);
char ans;
for(int i=0;i<s.size();i++){
cnt[s[i]-'a']++;
}
for(int i=0;i<t.size();i++){
cnt[t[i]-'a']--;
if(cnt[t[i]-'a'] < 0)ans = t[i];
}
return ans;
}
};
文章评论