Title
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.
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.
题目大意:判断是否存在这种对应关系,一一映射,注意是双向的。
题目和205差不多,不同的是那个是char-char,这个是char-string,所以用了两个map,其实也可以用一个map的,因为string大于一个字符,然后。。。。
Solution
//cpp:
class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char, int> map1;
unordered_map<string, int> map2;
istringstream istrstream(str);
string t;
vector<string> v;
while (istrstream >> t) {
v.push_back(t);
}
if (pattern.length() != v.size())
return false;
int i = 0;
for (i = 0; i < pattern.length(); i++) {
if (i >= v.size() || map1[pattern[i]] != map2[v[i]]) {
return false;
}
map1[pattern[i]] = i + 1;
map2[v[i]] = i + 1;
}
return true;
}
};
public boolean wordPattern(String pattern, String str) {
String[] words = str.split(" ");
if (words.length != pattern.length())
return false;
Map index = new HashMap();
for (Integer i=0; i<words.length; ++i)
if (index.put(pattern.charAt(i), i) != index.put(words[i], i))
return false;
return true;
}