【两次过】Lintcode 702. 连接两个字符串中的不同字符

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

样例

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

解题思路:

    设立两个哈希表m1与m2分别存储s1与s2,便于查找。

    先遍历s1,如果在m2中找到与之相等的元素则删除。再遍历s2,如果在m1中找到与之相等的元素同样删除。

    经过前面的操作,现在剩下的s1+s2就是结果。

    注意:erase操作后,指针已经指向了下一个元素,不需要再++。

              还有建立哈希表m1与m2时,一定要在未修改时建立,我第一次没过的原因是,在修改s1之后再建立的m1,这样肯定出错。

class Solution {
public:
    /**
     * @param s1: the 1st string
     * @param s2: the 2nd string
     * @return: uncommon characters of given strings
     */
    string concatenetedString(string &s1, string &s2) 
    {
        // write your code here
        unordered_map<char,int> m2;
        for(char c : s2)
            ++m2[c];
        
        unordered_map<char,int> m1;
        for(char c : s1)
            ++m1[c];
        
        for(int i=0;i<s1.size();)
        {
            if(m2.count(s1[i]))
                s1.erase(s1.begin()+i);
            else
                i++;
        }
        
        for(int i=0;i<s2.size();)
        {
            if(m1.count(s2[i]))
                s2.erase(s2.begin()+i);
            else
                i++;
        }
        
        return s1+s2;
    }
};


猜你喜欢

转载自blog.csdn.net/majichen95/article/details/80887033