leetcode解题: Word Pattern (290)

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.

解法1: HashMap, O(N + M)

这题对于我主要是学习C++的各种知识。。。 主要的思路是用两个map存储p到s的映射,也存储s到p的映射。
C++

1
2
3
4
读取一个string可以用到istringstream, 用法是istringstream ss(str);
然后读取ss中的string可以用getline(const istringstream&, const string& word, char delimiter)
getline如果返回为空则证明stream已经结束。
最后要判断getline是否为空是因为有可能str比pattern长。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
bool wordPattern(string pattern, string str) {
istringstream ss(str);
string word; // store the word from str
unordered_map<char, string> p2s;
unordered_map<string, char> s2p;
for (auto c : pattern) {
if (!getline(ss, word, ' ')) {
return false;
}
if (p2s.count(c) && p2s[c] != word) {
return false;
}
if (s2p.count(word) && s2p[word] != c) {
return false;
}
p2s[c] = word;
s2p[word] = c;
}
return !getline(ss, word, ' ');
}
};

Java

1