首页 > 其他分享 >leetcode-205-easy

leetcode-205-easy

时间:2022-10-25 18:46:16浏览次数:44  
标签:count map 205 String int easy return leetcode charAt

somorphic Strings

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

Two strings s and t 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
Constraints:

1 <= s.length <= 5 * 104
t.length == s.length
s and t consist of any valid ascii character.

思路一: 遍历字符串,不但要记录字符串还要记录字符串出现的次数,写的不太好

public boolean isIsomorphic(String s, String t) {
    if (s.length() != t.length()) return false;

    String c1 = count(s);
    String c2 = count(t);

    return c1.equals(c2);
}

private String count(String s) {
    StringBuilder s1 = new StringBuilder();
    char c = s.charAt(0);
    int count = 1;
    int x = 0;
    Map<Character, Integer> map = new HashMap<>();
    for (int i = 1; i < s.length(); i++) {
        if (s.charAt(i) == c) {
            count++;
        } else {
            if (map.containsKey(c)) {
                x = map.get(c);
            } else {
                map.put(c, x);
            }
            s1.append((char)x).append(count);
            c = s.charAt(i);
            count = 1;
            x = i;
        }
    }
    if (count > 0) {
        if (map.containsKey(c)) {
            x = map.get(c);
        }
        s1.append((char)x).append(count);
    }

    return s1.toString();
}

思路二: 用数学上的双射,用两个 map 记录两个字符串映射关系,如果映射关系出现变化,map 也会一起更新,一旦出现不一致,说明字符不一样

public boolean isIsomorphic2(String s, String t) {
    Map<Character, Character> s2t = new HashMap<>();
    Map<Character, Character> t2s = new HashMap<>();
    int len = s.length();
    for (int i = 0; i < len; ++i) {
        char x = s.charAt(i), y = t.charAt(i);
        if ((s2t.containsKey(x) && s2t.get(x) != y) || (t2s.containsKey(y) && t2s.get(y) != x)) {
            return false;
        }
        s2t.put(x, y);
        t2s.put(y, x);
    }
    return true;
}

标签:count,map,205,String,int,easy,return,leetcode,charAt
From: https://www.cnblogs.com/iyiluo/p/16825897.html

相关文章