leetcode 205. isomorphic string

leetcode 205. isomorphic string

Title Description

Given two strings s and t, it determines whether they are isomorphic.

S If the characters can be obtained by replacing t, then the two strings are isomorphic.

All characters appearing must be replaced with another character, while preserving the order of characters. Two characters can not be mapped to the same character, but the character itself can be mapped.

Example 1:

输入: s = "egg", t = "add"
输出: true

Example 2:

输入: s = "foo", t = "bar"
输出: false

Example 3:

输入: s = "paper", t = "title"
输出: true

Note:
You can assume s and t have the same length.

Problem-solving ideas

This topic focuses on understanding what the title of this sentence:Two characters can not be mapped to the same character, Meaning the character mapping is one to one relationship, not many or many-to, for example: s = "aabaa", t = "ccdee", s and t are not homogeneous string, since s -> process t of, 'a' mapping relation is 'a' -> 'c', 'a' -> 'e', ​​i.e., 'c' and 'e' simultaneously mapped on the 'a', so incompatible. So know the future, you can determine whether homogeneous by creating a hash table. First, we need to know s-> t process whether isomorphic mapping, then it is determined t-> s isomorphic if, at the same time when the two meet, can represent the s, t are isomorphic string. Why should we interpret it twice, for example: s = "bar", t = "foo", in the course map, see table below:

s->t t->s
‘b’->‘f’ ‘f’->‘b’
‘a’->‘o’ ‘o’->‘a’
‘r’->‘o’ ‘o’->‘r’

From the table, if the hash corresponds to establish thanks, s-> t in the process is to determine whether or not it is a homogeneous, but t-> s process, can be seen 'o' is not one to one, so twice interpretation, as well as the true time, can be determined string isomorphic

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        if(s.size() != t.size()){  // 如果两个字符串的长度不相等,表示两个是非同构字符串
            return false;
        }
        
        return helper(s, t) && helper(t, s);
    }

    bool helper(string str1, string str2){
        unordered_map<char, char> map;   //建立映射哈希表
        int len = str1.size();
        for(int i=0; i<len; i++){
            if(map.find(str1[i]) == map.end()){     // 表中是否存在,不存在添加数据
                map[str1[i]] = str2[i];
            }
            else{
                if(map[str1[i]] != str2[i]){       // 如果存在判断map的键对应的值是否和当前str2中的值相等,如果不相等表示存在一对多的问题,返回false
                    return false;
                }
            }
        }
        return true;
    }
};

Welcome to my personal public concern number, and also the same as the blog account, focus on sharing technical problems, we study together progress
Here Insert Picture Description

Published 135 original articles · won praise 164 · views 20000 +

Guess you like

Origin blog.csdn.net/EngineerHe/article/details/103840961