From bcb6cde23eda3c31fb3360caeb58a2b461811bcd Mon Sep 17 00:00:00 2001 From: ShusenTang Date: Sat, 25 Jul 2020 11:12:30 +0800 Subject: [PATCH] Update 290. Word Pattern.md --- solutions/290. Word Pattern.md | 36 ++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/solutions/290. Word Pattern.md b/solutions/290. Word Pattern.md index c70e8b3..f53cdc9 100644 --- a/solutions/290. Word Pattern.md +++ b/solutions/290. Word Pattern.md @@ -3,6 +3,11 @@ 类似[205. Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/description/), 所以解题思路基本一样。 将pattern和str中个每个元素都用一个数代替,这个数代表了该元素是第几个出现的(如 "abba" -> 1221, "dog cat cat dog" -> 1221), 则结果应该是一样的。 为了记录是否出现过,pattern用一个长度为26的数组实现,str用map来实现,此外还用一个count计数。 + +更新: + +可以用`istringstream`很方便地将`str`按照空格分开。 + # C++ ```C++ class Solution { @@ -32,3 +37,34 @@ public: } }; ``` + +更新: +``` C++ +class Solution { +public: + bool wordPattern(string pattern, string str) { + unordered_mapc_mp; + vectorc2int; + unordered_mapstr_mp; + + int count = 0; + for(char c: pattern){ + if(c_mp.find(c) == c_mp.end()) c_mp[c] = count++; + c2int.push_back(c_mp[c]); + } + + count = 0; + int i = 0; + string cur; + istringstream iss(str); + while(iss.good()){ // or !iss.eof() + iss >> cur; + if(str_mp.find(cur) == str_mp.end()) str_mp[cur] = count++; + if(i >= c2int.size() || c2int[i] != str_mp[cur]) return false; + i++; + } + + return i == c2int.size(); + } +}; +```