290. Word Pattern

Given apatternand a stringstr, find ifstrfollows the same pattern.

Herefollowmeans a full match, such that there is a bijection between a letter inpatternand anon-emptyword instr.

Examples:

  • pattern = "abba", str = "dog cat cat dog" should return true.
  • pattern = "abba", str = "dog cat cat fish" should return false.
  • pattern = "aaaa", str = "dog cat cat dog" should return false.
  • pattern = "abba", str = "dog dog dog dog" should return false.

Notes:
You may assumepatterncontains only lowercase letters, andstrcontains lowercase letters separated by a single space.

S: istringstream + hashmap

    bool wordPattern(string pattern, string str) {
        unordered_map<char, string> charToStr;
        unordered_set<string> strs;
        istringstream s(str);
        string word;
        int idx = 0;
        while (s >> word) {
            if (idx == pattern.size()) return false;
            if (charToStr.find(pattern[idx]) == charToStr.end()) {
                if (strs.find(word) == strs.end()) {
                    charToStr[pattern[idx]] = word;
                    strs.insert(word);
                } else {
                    return false;
                }
            } else if (charToStr[pattern[idx]] != word) {
                return false;
            }
            idx++;
        }
        return idx == pattern.size();
    }

results matching ""

    No results matching ""