给定两个字符串 s 和 t ,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例 1:
输入:s = "abcd", t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。
示例 2:
输入:s = "", t = "y"
输出:"y"
提示:
0 <= s.length <= 1000
t.length == s.length + 1
s 和 t 只包含小写字母
思路
首先对s和t进行排序。这样,如果s和t是相同的(除了t多一个字符),那么排序后的s和t应该是几乎相同的,只是t在某个地方多了一个字符。
然后,函数定义了两个迭代器it1和it2,分别指向s和t的开始。接着,有一个循环,只要it1没有到达s的末尾,就比较it1和it2指向的字符。如果这两个字符不同,那么it2指向的字符就是t相对于s多出的那个字符,因此函数返回*it2。
如果循环结束时还没有找到不同的字符,那么t相对于s多出的字符一定是t的最后一个字符。因此,函数返回t的最后一个字符,即*t.rbegin()。
AC代码
            
            
              cpp
              
              
            
          
          /*
 * @lc app=leetcode.cn id=389 lang=cpp
 *
 * [389] 找不同
 */
// @lc code=start
class Solution {
   public:
	char findTheDifference(string s, string t) {
		sort(s.begin(), s.end());
		sort(t.begin(), t.end());
		auto it1 = s.begin();
		auto it2 = t.begin();
		for (; it1 != s.end(); it1++, it2++) {
			if (*it1 != *it2) {
				return *it2;
			}
		}
		return *t.rbegin();
	}
};
// @lc code=end