[LeetCode]389. Find the Difference(找不同)

    xiaoxiao2021-03-25  55

    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. 题目大意: 给定两个只由小写字母组成的字符串s和t。 字符串t由字符串s 随机洗牌(打乱顺序) 生成,然后在随机位置添加一个字母。 找到在t中添加的字母。 Example:

    Input: s = "abcd" t = "abcde" Output: e Explanation: 'e' is the letter that was added.

    思路:遍历两个字符串,将t中与s相同的字符统统赋值为’0’,剩下的一个未被赋值的字符即为要找的字母

    代码如下:

    C++ #include <iostream> #include <string> using namespace std; class Solution { public: char findTheDifference(string s, string t) { int s_length = s.length(); int t_length = t.length(); for(int i=0;i<s_length;i++)//遍历字符串s { for(int j=0;j<t_length;j++)//遍历字符串t { if(s[i] == t[j])//若在字符串t中 找到与 字符串s中元素 相同的字符 { t[j] = '0';//将t中该元素赋值'0' break;//并结束遍历字符串t } } } for(int m=0;m<t_length;m++)//遍历字符串t { if(t[m] != '0')//找到没有被赋值为'0'的元素 返回该值 return t[m]; } return t[s_length]; } }; int main() { Solution a; cout << a.findTheDifference("aa", "aea") << endl; return 0; }

    注意:

    将t中元素重新赋值后一定要结束遍历t,并进行遍历下一个s中元素。否则会把t中相同元素全部赋值为’0’ 例如:s = “ae”; t = “aae”; 遍历s中的a时,就会把t中所有的a全部赋值’0’,最后结果得不到正确值break;结束当前for循环(遍历t的循环)但不会结束外层for循环(遍历s的循环)该方法思路简单但是时间复杂度比较大http://blog.csdn.net/qq508618087/article/details/52352635查看其它博客,有用异或方法http://www.cnblogs.com/qinduanyinghua/p/5827777.html 用Hash表方法http://blog.csdn.net/Xiejingfa/article/details/50469045【C++11新特性】 auto关键字
    转载请注明原文地址: https://ju.6miu.com/read-35477.html

    最新回复(0)