We are given two sentences A and B.  (A sentence is a string of space separated words.  Each word consists only of lowercase letters.)

A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.

Return a list of all uncommon words. 

You may return the list in any order.

 

Example 1:

Input: A = "this apple is sweet", B = "this apple is sour"
Output: ["sweet","sour"]
Example 2:

Input: A = "apple apple", B = "banana"
Output: ["banana"]
 

Note:

0 <= A.length <= 200
0 <= B.length <= 200
A and B both contain only spaces and lowercase letters.

这题没啥说的,会切分字符串和使用map就可以了。

class Solution {
public:
    vector<string> uncommonFromSentences(string A, string B) {
        vector<string> substrs;
        unordered_map<std::string, int> words;
        std::string full_str = A + ' ' + B;

        std::size_t pos = 0;
        while (pos != std::string::npos) {
            std::size_t cur_pos = full_str.find(' ', pos);
            std::string substr;
            if (cur_pos == std::string::npos) {
                substr = full_str.substr(pos, full_str.size() - 1 - pos + 1);
                pos = cur_pos;
            } else {
                substr = full_str.substr(pos, cur_pos - pos);
                pos = cur_pos + 1;
            }

            auto it = words.find(substr);
            if (it == words.end()) {
                words.insert(std::make_pair(std::move(substr), 1));
            } else {
                it->second++;
            }
        }

        for (auto & pa : words) {
            if (pa.second == 1) {
                substrs.push_back(pa.first);
            }
        }
        return substrs;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day