题目:
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 in str.
Example 1:Input: pattern = "abba", str = "dog cat cat dog" Output: true
Example 2:
Input:pattern = "abba", str = "dog cat cat fish" Output: false
Example 3:
Input: pattern = "aaaa", str = "dog cat cat dog" Output: false
Example 4:
Input: pattern = "abba", str = "dog dog dog dog" Output: false
Notes:
You may assumepattern
contains only lowercase letters, andstr
contains lowercase letters separated by a single space.
解释:
双向映射,应该用两个map做,和205. Isomorphic Strings(python+cpp)的写法是一样的。
一个字典的写法,python代码:
class Solution(object):
def wordPattern(self, pattern, _str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
_str=_str.split()
_dict={}
if len(pattern)!=len(_str):
return False
for i in xrange(len(pattern)):
if pattern[i] not in _dict and _str[i] not in _dict.values():
_dict[pattern[i]]=_str[i]
else:
if pattern[i] not in _dict or _dict[pattern[i]]!=_str[i]:
return False
return True
不用一个字典因c++的<map>
无法获values()为一个数组。
两个字典的写法(速度更快):
python代码:
class Solution(object):
def wordPattern(self, pattern, _str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
_str=_str.split()
if len(pattern)!=len(_str):
return False
pattern_dict={}
_str_dict={}
for i in range(len(pattern)):
if pattern[i] not in pattern_dict:
pattern_dict[pattern[i]]=_str[i]
else:
if pattern_dict[pattern[i]]==_str[i]:
continue
else:
return False
if _str[i] in _str_dict:
if _str_dict[_str[i]]!=pattern[i]:
return False
else:
_str_dict[_str[i]]=pattern[i]
return True
c++要首先先把str分割一下,用istringstream
c++代码:
#include<sstream>
using namespace std;
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string>str_list;
istringstream strstream(str);
string word="";
while(getline(strstream,word,' '))
{
str_list.push_back(word);
}
if (pattern.size()!=str_list.size())
return false;
map<char,string> pattern_map;
map<string,char> str_map;
for(int i=0;i<pattern.size();i++)
{
if (!pattern_map.count(pattern[i]))
pattern_map[pattern[i]]=str_list[i];
else
{
if (pattern_map[pattern[i]]==str_list[i])
continue;
else
return false;
}
if (str_map.count(str_list[i]))
{
if (str_map[str_list[i]]!=pattern[i])
return false;
}
else
str_map[str_list[i]]=pattern[i];
}
return true;
}
};
总结:
和之前那道题的写法是一模一样的,恩。