Leetcode 884. Uncommon Words from Two Sentences

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/83477390

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Uncommon Words from Two Sentences

2. Solution

  • Version 1
class Solution {
public:
    vector<string> uncommonFromSentences(string A, string B) {
        vector<string> result;
        unordered_map<string, int> m;
        string s;
        for(char ch : A) {
            if(ch != ' ') {
                s += ch;
            }
            else {
                m[s]++;
                s = "";
            }
        }
        m[s]++;
        s = "";
        for(char ch : B) {
            if(ch != ' ') {
                s += ch;
            }
            else {
                m[s]++;
                s = "";
            }
        }
        m[s]++;
        for(auto pair : m) {
            if(pair.second == 1) {
                result.emplace_back(pair.first);
            }
        }
        return result;
    }
};
  • Version 2
class Solution {
public:
    vector<string> uncommonFromSentences(string A, string B) {
        vector<string> result;
        unordered_map<string, int> m;
        istringstream strA(A);  
        string s;  
        while(strA >> s) {
            m[s]++;    
        }
        istringstream strB(B); 
        while(strB >> s) {
            m[s]++;    
        }
        for(auto pair : m) {
            if(pair.second == 1) {
                result.emplace_back(pair.first);
            }
        }
        return result;
    }
};

Reference

  1. https://leetcode.com/problems/uncommon-words-from-two-sentences/description/

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试