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 inpattern and a
non-empty word in str.
Examples:
- pattern =
"abba", str ="dog cat cat dog"should return true ::::: map[a] = 1, map[dog] = 1; map[b] = 1, map[cat] = 1; map[b] = 2, map[cat] = 2; map[a] = 2, map[dog] = 2 ---->true
- pattern =
"abba", str ="dog cat cat fish"should return false. ::::: map[a] = 1, map[dog] = 1'; map[b] = 1, map[cat] = 1; map[b] = 2, map[cat] = 2; map[a] = 2, map[fish] = 1 ----> false
- pattern =
"aaaa", str ="dog cat cat dog"should return false. ::::: map[a] = 1, map[dog] = 1; map[a] = 2, map[cat] = 1 ---->false
- pattern =
"abba", str ="dog dog dog dog"should return false. :::: map[a] = 1, map[dog] = 1; map[b] = 1, map[dog] = 2 ---> false
It will cost a lot of energy if trying to split the words..... it is good to use stringstream!
bool wordPattern(string pattern, string str) {
vector<string> words;
stringstream s(str);
string word;
while(s >> word) words.push_back(word);
if(words.size() != pattern.size()) return false;
unordered_map<string ,int> map_1;
unordered_map<char, int> map_2;
for(int i = 0; i < pattern.size(); ++i) {
if(map_1[words[i]] || map_2[pattern[i]]) {
if(map_1[words[i]] != map_2[pattern[i]]) return false;
} else {
map_1[words[i]]++;
map_2[pattern[i]]++;
}
}
return true;
}Another way:
#include <string>
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
using namespace std;
bool wordPattern(string pattern, string words) {
int cnt = 0;
stringstream in(words);
string word;
/* we only need to set up one map. char to string.*/
/* the words need a set to check if it is already there.*/
unordered_map<char, string> hash1;
unordered_set<string> hash2;
while(in >> word) {
if(cnt == pattern.size()) return false;
if(hash1.find(pattern[cnt]) == hash1.end() && hash2.find(word) == hash2.end()) {
hash1.insert({pattern[cnt], word});
hash2.insert(word);
} else if(hash1[pattern[cnt]] != word) return false;
cnt++;
}
return cnt == pattern.size();
}
int main(void) {
cout << wordPattern("abc", "word, words, wordses") << endl;
cout << wordPattern("aab", "word word words") << endl;
cout << wordPattern("aab", "word words words") << endl;
cout << wordPattern("aba", "word words word") << endl;
}
本文探讨了如何通过算法判断给定字符串是否遵循特定模式,包括模式与字符串间的映射关系,以及使用streaming和unordered_map等数据结构提高效率。
715

被折叠的 条评论
为什么被折叠?



