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的字符个数标记在hash1和hash2数组中,然后比较hash1和hash2,值不同的那个字符即为所求~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Solution { public: char findTheDifference(string s, string t) { int hash1[256] = {0}, hash2[256] = {0}; for(int i = 0; i < s.length(); i++) hash1[s[i]]++; for(int i = 0; i < t.length(); i++) hash2[t[i]]++; for(int i = 0; i < 256; i++) if(hash1[i] != hash2[i]) return (char)i; return '0'; } }; |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼