1. 算法描述
給定匹配格式,判斷字符串是否符合格式。
單詞字符串需要完全符合給定的匹配格式,格式字符串和單詞字符串有雙射關係。
Example 1:
Input: pattern = “abba”, str = “dog cat cat dog”
Output: true
Example 2:
Input:pattern = “abba”, str = “dog cat cat fish”
Output: false
Example 3:
Input: pattern = “aaaa”, str = “dog cat cat dog”
Output: false
Example 4:
Input: pattern = “abba”, str = “dog dog dog dog”
Output: false
2. 思想分析
(1)如果是格式字符串是迴文,那麼單詞字符串也需要是迴文格式;
(2)如果是單一重複字符串,那麼單詞字符串所有單詞也一樣;
(3)如果都是不一樣的字符,那麼單詞字符串所有單詞也不一樣;
…
但是算法總不能每種情況分別處理,需要找到規律:
Step 1. 分割單詞字符串,存放在一個vector中;
Step 2. 準備兩個map, 一個用來標記格式字符串中每個字符的位置;
另一個用來標記單詞在Step1 Vector中的位置
Step3. 比較位置信息,如果不一致,return false.
3. 參考代碼
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> vectStr;
string tmpStr;
map<char, vector<int>> mapPattern;
map<string, vector<int>> mapStr;
int i = 0;
for (i = 0; i < str.length(); i++)
{
if (str[i] == ' ')
{
vectStr.push_back(tmpStr);
tmpStr.clear();
}
else
{
tmpStr.push_back(str[i]);
}
if ( i == str.length() - 1) vectStr.push_back(tmpStr);
}
if (pattern.size() != vectStr.size()) return false;
for (i = 0; i < pattern.length(); i++)
{
mapPattern[pattern[i]].push_back(i);
mapStr[vectStr[i]].push_back(i);
if (mapPattern[pattern[i]] != mapStr[vectStr[i]]) return false;
}
return true;
}
};