每天一道LeetCode-----判断给定字符串是否符合某个模式

Isomorphic Strings

原题链接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

原题链接Word Pattern

判断一个字符串中的单次是否按照给定模式排列

思路:

仍然是一对一的关系,和上面的类似

扫描二维码关注公众号,回复: 1130209 查看本文章

代码如下

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;
    }
};

猜你喜欢

转载自blog.csdn.net/sinat_35261315/article/details/79456110
今日推荐