這個hash的模式之前也用過,Isomorphic Strings這道題用過,就是搞兩個表,對兩個比較的模式,key塞字符串,值塞第一次出現的位置,然後兩個表的字符串,如果是對應的,那麼相應的key的值是一樣的,如果不對應(模式不一樣),那麼相應的key的值就不一樣。
還有一個就是字符串有空格,怎樣拆分,這裏用了一個流的模式:
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> word;
stringstream ss(str);
string str1;
while(ss>>str1)
{
word.push_back(str1);
}
if(pattern.length()!=word.size())
{
return false;
}
unordered_map<char,int> pat;
unordered_map<string,int> st;
for(int i=0;i<pattern.size();i++)
{
if(pat.find(pattern[i])==pat.end()&&st.find(word[i])==st.end())
{
pat[pattern[i]]=i+1;
st[word[i]]=i+1;
}
else if(pat.find(pattern[i])!=pat.end()&&st.find(word[i])!=st.end())
{
if(pat[pattern[i]]!=st[word[i]])
return false;
}
else
return false;
}
return true;
}
};
這是另一種,和我的思路是一樣的,區別是它以str爲主,用流輸出,然後兩個是否等長在過程中和結尾判斷,i==n是判斷是否等長的。然後map我的有key是否存在的界限,這個其實可以不判定,如果key沒有,你用了比如pat[a],那麼就相當於是一個構造函數了,初始值構造成了0.
bool wordPattern(string pattern, string str) {
map<char, int> p2i;
map<string, int> w2i;
istringstream in(str);
int i = 0, n = pattern.size();
for (string word; in >> word; ++i) {
if (i == n || p2i[pattern[i]] != w2i[word])
return false;
p2i[pattern[i]] = w2i[word] = i + 1;
}
return i == n;
}