【leetcode】205. Isomorphic Strings

题目:
Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.


思路:

  • 思路1: 为字符串s和t设置两个map,使得对应字符形成一一对应的关系。
  • 思路2: 对于字符串s和t,设置两个map,保存上次出现的位置。每次迭代时,判断两字符(s[i]和t[i])上次出现的位置是否相同。

代码实现:
思路1:

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        unordered_map<char, char> s_map;
        unordered_map<char, char> t_map;
        
        for (int i = 0; i < s.size(); ++i){
            if (s_map.find(s[i]) != s_map.end()){
                if (s_map[s[i]] != t[i]){
                    return false;
                }
            }else{
                if (t_map.find(t[i]) != t_map.end()){
                    return false;
                }
                s_map[s[i]] = t[i];
                t_map[t[i]] = s[i];
            }
        }
        
        return true;
    }
};

思路2:

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        unordered_map<char, int> s_map;
        unordered_map<char, int> t_map;
        
        for (int i = 0; i < s.size(); ++i){
            if (s_map.find(s[i]) !=  s_map.end() && t_map.find(t[i]) != t_map.end()){
                if (s_map[s[i]] != t_map[t[i]]){
                    return false;
                }
            }else if(s_map.find(s[i]) ==  s_map.end() && t_map.find(t[i]) == t_map.end()){
                s_map[s[i]] = i;
                t_map[t[i]] = i;
            }else{
                return false;
            }
        }
        
        return true;
    }
};
原创文章 299 获赞 2 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zxc120389574/article/details/106034249