원티드 프리온보딩 - BE/과제 정리

[HashTable] 205. Isomorphic Strings

고마우미 2023. 9. 1. 08:25

 

문제

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 * 10^4t.
length == s.lengths and t consist of any valid ascii character.

 

 

문제 접근

1. 2개의 해쉬맵을 선언한다.

2. s의 문자를 t의 문자로, t의 문자를 s의 문자로 저장한다.

3. 치환 문자가 일치 하지 않은 경우 fasle를 반환한다.

 

문제 풀이

class Solution {
    public boolean isIsomorphic(String s, String t) {
        
        HashMap<Character, Character> hm = new HashMap(); 
        HashMap<Character, Character> hm2 = new HashMap(); 


        for(int i = 0; i < s.length(); i++){
    
            if(hm.get(s.charAt(i)) == null){
                hm.put(s.charAt(i), t.charAt(i));
            }else{
                if(hm.get(s.charAt(i)) != t.charAt(i)) return false;
            }

            if(hm2.get(t.charAt(i)) == null){
                hm2.put(t.charAt(i), s.charAt(i));
            }else{
                if(hm2.get(t.charAt(i)) != s.charAt(i)) return false;
            }
        }

        return true;
    }
}