290. Word Pattern

양성준·2025년 5월 6일

코딩테스트

목록 보기
44/102

문제

https://leetcode.com/problems/word-pattern/description/

풀이

class Solution {
    public boolean wordPattern(String pattern, String s) {
        Map<Character, Integer> map1 = new HashMap<>();
        String[] arr = s.split(" ");
        Map<String, Integer> map2 = new HashMap<>();

        if(pattern.length() != arr.length) {
            return false;
        }

        for(int i = 0; i < pattern.length(); i++) {
            char c = pattern.charAt(i);
            String t = arr[i];

           if(!map1.containsKey(c)) {
              map1.put(c, i);
           }

           if(!map2.containsKey(t)) {
              map2.put(t, i);
           }

           if(!map1.get(c).equals(map2.get(t))) return false;
        }

        return true;
    }
}
profile
백엔드 개발자

0개의 댓글