LeetCode-Isomorphic Strings

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/89486093

Description:
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 s and t have the same length.

题意:判断两个字符串 s s t t 是否为同构的,同构的定义为将字符串 s s 中的每个相同字符映射为另外一个字符后可以与字符串 t t 相同,则这两个字符串为同构的;例如:对于字符串"egg"和add"

e a g d g d e \rightarrow a \\ g \rightarrow d \\ g \rightarrow d \\

解法:要判断两个字符串为同构的,我们考虑将字符串的每个相同字符映射为数字形式,例如对于 " e g g " " 122 " "egg" \rightarrow "122" ,将两个字符串同样以这种方式映射为数字形式,如果最后两个字符串的数字形式相同,说明是同构的;

Java
class Solution {
    public boolean isIsomorphic(String s, String t) {
        return shape(s).equals(shape(t));
    }
    
    private String shape(String s) {
        Map<Character, Integer> map = new HashMap<>();
        int ind = 0;
        StringBuilder sb = new StringBuilder();
        for (char ch: s.toCharArray()) {
            if (!map.containsKey(ch)) {
                map.put(ch, ind);
                ind++;
            }
            sb.append(map.get(ch));
        }
        return sb.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/89486093
今日推荐