LeetCode - 205. Isomorphic Strings(Hash Table, String)

YAMAMAMO·2022년 2월 27일
0

LeetCode

목록 보기
33/100

문제

두 문자열 s와 t가 주어졌을 때, 그것들이 동형인지 판단한다.
s의 문자를 대체하여 t를 얻을 수 있다면 두 문자열 s와 t는 동형이다.
문자의 모든 발생은 문자의 순서를 유지하면서 다른 문자로 대체되어야 합니다. 두 개의 문자는 동일한 문자에 매핑할 수 없지만, 문자는 그 자체로 매핑할 수 있습니다.

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

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

풀이

자바입니다.

  • 주어진 문자열의 구조를 ArrayList에 담습니다.
    ex) egg -> [0,1,1], add -> [0,1,1], paper -> [0,1,0,2,3]
  • charAt()을 사용해서 String s의 문자열을 한글자씩 출력합니다.
  • constainsKey()를 사용해서 key가 있는지 확인합니다.
  • key가 있으면 같은 글자가 있다는 뜻입니다.
class Solution {
    public boolean isIsomorphic(String s, String t) {
        HashMap<Character, Integer> hash = new HashMap<>();
        ArrayList<Integer> list = new ArrayList<>();
        int j=0;
        for(int i=0;i<s.length();i++){
            char str = s.charAt(i);
            if(hash.containsKey(str)){
                list.add(hash.get(str));
            }else{
                hash.put(str,j);
                list.add(j);
                j++;
            }
        }
        hash.clear();
        j=0;
        for(int i=0;i<t.length();i++){
            char str = t.charAt(i);
            int con = 0;
            if(hash.containsKey(str)){
                con = hash.get(str);
            }else{
                hash.put(str,j);
                con = j;
                j++;
            }
            if(list.get(i)!=con) return false;
        }
        
        return true;
    }
}
profile
안드로이드 개발자

0개의 댓글