LeetCode 389. Find the Difference (字符串比较)

来源:互联网 发布:mysql 查询一年总数 编辑:程序博客网 时间:2024/06/14 22:40

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:eExplanation:'e' is the letter that was added.
输入两个字符串s和t,t是将s打乱顺序后在任意位置插入一个字符后形成的字符串,找到这个字符。

思路:将string转为vector<char>后排序,逐个比较。

也可以利用A xor B xor A = B 的性质,用异或来算。

char findTheDifference(string s, string t) {        vector<char> ss(0);        vector<char> tt(0);        int i;        for(i=0;i<s.size();i++)            ss.push_back(s[i]);        for(i=0;i<t.size();i++)            tt.push_back(t[i]);        sort(ss.begin(),ss.end());        sort(tt.begin(),tt.end());        for(i=0;i<s.size();i++)        {            if(ss[i]!=tt[i])                return tt[i];        }        return tt[tt.size()-1];    }




原创粉丝点击