每天一道LeetCode-----判斷給定字串是否符合某個模式
阿新 • • 發佈:2019-02-01
Isomorphic Strings
給定兩個字串,判斷其中一個是否能轉換成另一個,轉換規則如下
- 必須是一對一
- 同一個字元兩次轉換必須相同,如果第一次字元’a’轉換成’b’,那麼當下次遇到’a’時,它就只能轉換成’b’
- 不能有兩個字元轉換成相同字元,如果第一次’a’轉換成’b’,那麼之後其它的字元都不能再轉換成’b’
思路:
通過兩個陣列記錄轉換規則,直到轉換完成
程式碼如下
class Solution {
public:
bool isIsomorphic(string s, string t) {
vector<int> nums(256 , 0);
vector<int> count(256, 0);
for(int i = 0; i < s.size(); ++i) {
/* 之前沒有轉換過,記錄轉換規則 */
if(nums[s[i]] == 0 && count[t[i]] == 0) {
nums[s[i]] = t[i];
count[t[i]] = 1;
}
/* 當nums[s[i]] == t[i]時正確,否則返回false */
else if(nums[s[i]] != t[i]) {
return false;
}
}
return true;
}
};
Word Pattern
判斷一個字串中的單次是否按照給定模式排列
思路:
仍然是一對一的關係,和上面的類似
程式碼如下
class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char , string> hash;
unordered_map<string, int> count;
std::istringstream oss(str);
std::string line;
for(auto ch : pattern) {
std::getline(oss, line, ' ');
if(hash.count(ch) == 0 && count.count(line) == 0) {
hash[ch] = line;
count[line] = 1;
}
else if(hash[ch] != line) {
return false;
}
}
return std::getline(oss, line) ? false : true;
}
};