LeetCode205 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.

Example 1:

Input: s = "egg", t = "add"
Output: true

Example 2:

Input: s = "foo", t = "bar"
Output: false

Example 3:

Input: s = "paper", t = "title"
Output: true

Note:
You may assume both and have the same length.

题源:here

思路

这道题的关键是理解题意:S中和T中元素都不能映射两次。

解法1

两个map,一个s-t,一个t-s,如果发现映射不同元素的情况就返回false。

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

解法2

在解法1的基础上进行改进,我们认为当t中的元素被访问过时,他就有一个映射,如果s中没有这个元素的映射,那么就应该返回false。

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        char map[256]={0};
        bool vis[256] ={false};
        for(int i=0;i<int(s.size());i++){
            if(map[s[i]] == 0){
                if(vis[t[i]] == true) return false;
                map[s[i]] = t[i];
                vis[t[i]] = true;
            }
            else if(map[s[i]] != t[i]) return false;
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/88640110