본문 바로가기

Algorithm

[leetcode 75] 205. Isomorphic Strings

문제해석

s의 문자열을 t의 문자열로 대체 가능한 경우 Isomorphic이라고 한다

각 문자는 문자의 숫자를 유지하면서 대체가능하여야 하는데 문자 하나가 여러개를 대체할 수 없고 자기 자신은 그대로 대체할 수 있다

 

예시

Example 1:

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

e > a로, g가 d로 대체될 수 있으므로 true

 

Example 2:

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

f > b로 대체될 수 있지만 o가 a와 r 두개의 문자로 대체될 수 없으므로 false

 

Example 3:

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

p > t, a > i, e > l, r > e로 대체할 수 있으므로 true

 

정답 예

public boolean isIsomorphic(String s, String t) {
    Map<Character, Character> map1 = new HashMap<>();
    Map<Character, Character> map2 = new HashMap<>();

    char[] schar = s.toCharArray();
    char[] tchar = t.toCharArray();

    for (int i=0; i < schar.length; i++) {
        // 변환될 수 있는 char를 map에 담아
        map1.put(schar[i], tchar[i]);
        map2.put(tchar[i], schar[i]);
    }

    for (int i=0; i < schar.length; i++) {
        // 변환시켜서 비교 s > t
        Character c1 = map1.get(schar[i]);
        if (c1 == null || c1.charValue() != tchar[i]) {
            return false;
        }

        // 변환시켜서 비교 t > s
        Character c2 = map2.get(tchar[i]);
        if (c2 == null || c2.charValue() != schar[i]) {
            return false;
        }
    }

    return true;
}