一天一道LeetCode
本系列文章已全部上傳至我的github,地址:ZeeCoder‘s Github
歡迎大家關注我的新浪微博,我的新浪微博
歡迎轉載,轉載請註明出處
(一)題目
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.
(二)解題
題目大意:字符串模式匹配。給定模板字符串pattern和待匹配字符串str,判斷str是否與pattern模式匹配
解題思路:這是一道典型應用hash表求解的題。
利用兩個輔助的hash表實現字符串的雙向匹配。例如a->dog,dog->a
不允許出現模式中兩個不同的字符對應str中同一個單詞。
具體思路見代碼:
class Solution {
public:
bool wordPattern(string pattern, string str) {
int lenp=pattern.length();
int lens=str.length();
int i = 0;
int j = 0;
unordered_map<string,char> hash;//兩個hash表,雙向匹配
unordered_map<char,string> hash2;
while(i<lenp&&j<lens){
string temp;
while(j<lens&&str[j]!=' '){//找出str中以空格分隔的字符串
temp+=str[j++];
}
auto iter = hash.find(temp);
auto iter2 = hash2.find(pattern[i]);
if(iter==hash.end()&&iter2==hash2.end()){//如果都不存在
hash[temp] = pattern[i];
hash2[pattern[i]] = temp;//記錄雙向匹配關係
}
else{
if(hash[temp]==pattern[i]&&hash2[pattern[i]]==temp) {}
else return false;//匹配不上
}
i++;j++;
}
return i>=lenp?j>=lens?true:false:false;//最後需要判斷兩個字符串是否匹配完
}
};