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,将s打乱顺序后随机插入一个字符,找到这个字符。
理 解:
方法一:数组统计法。
数组统计s中所有字符出现的次数。遍历t时每遇到一个字符-1,当计数为-1时,找到该字符。
方法二:直接法。
用t所有字符和减s所有字符和,即为该字符。
代 码 C++:
方法一:
class Solution { public: char findTheDifference(string s, string t) { vector<int> count(26); for(char ch:s){ count[ch-‘a‘]++; } for(char ch:t){ count[ch-‘a‘]--; if(count[ch-‘a‘]==-1) return ch; } return ‘ ‘; } };
方法二:
class Solution { public: char findTheDifference(string s, string t) { int sum = 0; for(char ch:t){ sum += ch; } for(char ch:s){ sum -= ch; } return sum; } };
运行结果:
方法一:
方法二:
letecode [389] - Find the Difference
原文:https://www.cnblogs.com/lpomeloz/p/11054469.html