LeetCode 290. Word Pattern

Given a pattern and a string str, find if str follows the same pattern.

Here follow means a full match, such that there is a bijection between a letter inpattern and a non-empty word in str.

Examples:

  1. pattern = "abba", str = "dog cat cat dog" should return true ::::: map[a] = 1, map[dog] = 1;  map[b] = 1, map[cat] = 1; map[b] = 2, map[cat] = 2; map[a] = 2, map[dog] = 2 ---->true
  2. pattern = "abba", str = "dog cat cat fish" should return false. ::::: map[a] = 1, map[dog] = 1'; map[b] = 1, map[cat] = 1; map[b] = 2, map[cat] = 2; map[a] = 2, map[fish] = 1 ----> false
  3. pattern = "aaaa", str = "dog cat cat dog" should return false. ::::: map[a] = 1, map[dog] = 1; map[a] = 2, map[cat] = 1 ---->false
  4. pattern = "abba", str = "dog dog dog dog" should return false. :::: map[a] = 1, map[dog] = 1; map[b] = 1, map[dog] = 2 ---> false


It will cost a lot of energy if trying to split the words..... it is good to use stringstream!

    bool wordPattern(string pattern, string str) {
        vector<string> words;
        stringstream s(str);
        string word;
        while(s >> word) words.push_back(word);
        
        if(words.size() != pattern.size()) return false;
        unordered_map<string ,int> map_1;
        unordered_map<char, int> map_2;
        
        for(int i = 0; i < pattern.size(); ++i) {
            if(map_1[words[i]] || map_2[pattern[i]]) {
                if(map_1[words[i]] != map_2[pattern[i]]) return false;
            } else {
                map_1[words[i]]++;
                map_2[pattern[i]]++;
            }
        }
        return true;
    }


Another way:

#include <string>
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
using namespace std;

bool wordPattern(string pattern, string words) {
  int cnt = 0;
  stringstream in(words);
  string word;
  /* we only need to set up one map. char to string.*/
  /* the words need a set to check if it is already there.*/
  unordered_map<char, string> hash1;
  unordered_set<string> hash2;
  while(in >> word) {
    if(cnt == pattern.size()) return false;
    if(hash1.find(pattern[cnt]) == hash1.end() && hash2.find(word) == hash2.end()) {
      hash1.insert({pattern[cnt], word});
      hash2.insert(word);
    } else if(hash1[pattern[cnt]] != word) return false;
    cnt++;
  }
  return cnt == pattern.size();
}

int main(void) {
  cout << wordPattern("abc", "word, words, wordses") << endl;
  cout << wordPattern("aab", "word word words") << endl;
  cout << wordPattern("aab", "word words words") << endl;
  cout << wordPattern("aba", "word words word") << endl;
}


你可能感兴趣的:(LeetCode 290. Word Pattern)