給定一個模式字串 pattern(僅含小寫字母)和一個字串 str(單詞以單一空格分隔),判斷 str 是否遵循相同模式。這裡的「遵循」意味著雙向一一對應:pattern 中的每個字元唯一對應 str 中的一個非空單詞,反之亦然。
| pattern | str | 結果 |
|---|---|---|
| abba | dog cat cat dog | true |
| abba | dog cat cat fish | false |
| aaaa | dog cat cat dog | false |
| abba | dog dog dog dog | false |
核心難點在於建立 雙向映射:
char → word)無法檢測「不同字元對應相同單詞」的情況(如 abba vs dog dog dog dog)。map 和 map,確保一一對應。str 按空格分割為單詞陣列 words。pattern.length() != words.size(),直接返回 false。pattern 與 words:
false。true。class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map char2word;
unordered_map word2char;
vector words;
// 分割字串
for (int i = 0, j = 0; i <= str.size(); ++i) {
if (i == str.size() || str[i] == ' ') {
words.push_back(str.substr(j, i - j));
j = i + 1;
}
}
if (pattern.size() != words.size()) return false;
for (int i = 0; i < pattern.size(); ++i) {
char c = pattern[i];
const string& w = words[i];
if (!char2word.count(c) && !word2char.count(w)) {
char2word[c] = w;
word2char[w] = c;
} else if (char2word[c] != w || word2char[w] != c) {
return false;
}
}
return true;
}
};
O(n),n 為字串長度,分割與遍歷皆為線性。O(m),m 為不同字元/單詞數量,雜湊表儲存映射。stringstream、getline 或手動雙指標。