[Leetcode] #290 Word Pattern (map,sstream)

来源:互联网 发布:php注册短信验证 编辑:程序博客网 时间:2024/06/07 03:04

Discription:

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 in pattern and a non-empty word instr.

Examples:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. pattern = "abba", str = "dog dog dog dog" should return false.

Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

Solution:

bool wordPattern(string pattern, string str) {istringstream strcin(str);string s;vector<string> vs;while (strcin >> s) vs.push_back(s);if (pattern.size() != vs.size()) return false;unordered_map<string, int> s2i;unordered_map<char, int> c2i;for (int i = 0; i < vs.size(); ++i) {if (s2i[vs[i]] != c2i[pattern[i]])return false;s2i[vs[i]] = c2i[pattern[i]] = i + 1;}return true;}

0 0