连接两个字符串中的不同字符-LintCode

来源:互联网 发布:mac免费office软件 编辑:程序博客网 时间:2024/05/18 01:15

给出两个字符串, 你需要修改第一个字符串,将所有与第二个字符串中相同的字符删除, 并且第二个字符串中不同的字符与第一个字符串的不同字符连接

样例:
给出 s1 = aacdb, s2 = gafd
返回 cbgf
给出 s1 = abcs, s2 = cxzca;
返回 bsxz

思路:
利用set,先将s2中的字符存入set1。遍历s1,将不在set1中的字符添加到字符串str中,在set1中的字符存入set2。遍历s2,将不在set2中的字符添加到str中。

#ifndef C702_H#define C702_H#include<iostream>#include<set>#include<string>using namespace std;class Solution {public:    /*    * @param : the 1st string    * @param : the 2nd string    * @return: uncommon characters of given strings    */    string concatenetedString(string &s1, string &s2) {        // write your code here        if (s1.empty())            return s2;        if (s2.empty())            return s1;        set<char> set1;        set<char> set2;        for (auto c : s2)            set1.insert(c);        string str;        for (auto c : s1)        {            if (set1.find(c) == set1.end())                str += c;            else                set2.insert(c);        }        for (auto t : s2)        {            if (set2.find(t) == set2.end())                str += t;        }        return str;    }};#endif
阅读全文
0 0
原创粉丝点击