关关的刷题日记30 – 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的基础上随机加了个字符,让找出该字符。
思路:建一个map,key存字符s的每个字符,value存该字符的数量。然后遍历t的每个字符,将对应的map中该字符数量减1,最终map中哪个key对应的value值为-1,就是所求结果。写的时候要注意语法,范围for作用在map上的时候,注意map中的每个元素是pair,所以要用auto。
class Solution {public:
char findTheDifference(string s, string t) {
map<char,int>m;
for(char x:s)
{
m[x]++;
}
for(char y:t)
{
m[y]--;
}
for(auto z:m)
{
if(z.second==-1)
return z.first;
}
return NULL;
}};
人生易老,唯有陪伴最长情,加油!
以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang,注明Leetcode刷题)。