头图

title: Daily practice (43): isomorphic strings

categories:[Swords offer]

tags:[Daily practice]

date: 2022/04/15


Daily practice (43): isomorphic strings

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

If the characters in s can be replaced by some mapping to get t, then the two strings are isomorphic.

Each occurrence of a character should map to another character without changing the order of the characters. Different characters cannot be mapped to the same character, the same character can only be mapped to the same character, and a character can be mapped 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

hint:

1 <= s.length <= 5 * 104

t.length == s.length

s and t consist of any valid ASCII character

Source: LeetCode

Link: https://leetcode-cn.com/problems/isomorphic-strings

method one

Thought analysis

t.length == s.length so no need to consider length

The index found by find must be the same for the same character

Using this, we can use find to verify that the patterns are the same

  1. Suppose there are foo and baa, when we reach the last index, looking for 'o' in s and 'a' in t will definitely return
  2. The same index, because it has appeared before, here 'o' in s and 'a' in t will return index 1
  3. Also suppose we have foo and bar, 'fo' and 'ba' are fine, but when we get to the last index
  4. The 'o' in s will return 1 because it has appeared before, and the 'r' in t will return 2 because it has not been there before
  5. This letter has appeared, so you can verify that their patterns are the same
 bool isIsomorphic(string s, string t) {
    for (int i = 0; i < s.size(); ++i) {
        if (s.find(s[i]) != t.find(t[i])) {
            return false
        }
    }
    return true;
}

Method Two

Thought analysis

Connect edges and assign weights to characters with corresponding relationships. The initial value of 0 means that there is no mapping relationship, and only 0 can be used to connect edges.

So if it is a homogeneous string, the value of each pair of characters should be equal

 bool isIsomorphic(string s, string t) {
    int sm[128] = {0};
    int tm[128] = {0};
    for (int i = 0; i < s.size(); i++) {
        if (sm[s[i]] != tm[t[i]]) {
            return false;
        }
        sm[s[i]] = tm[t[i]] = i + 1;
    }
    return true;
}

加班猿
50 声望12 粉丝

记录一下生活的点滴,工作上遇到的问题以及学习上的各类笔记