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

xiaoxiao2021-02-28  88

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:

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 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; }GitHub-Leetcode: https://github.com/wenwu313/LeetCode

转载请注明原文地址: https://www.6miu.com/read-74516.html

最新回复(0)