티스토리 뷰

leetcode.com/problems/word-pattern/

 

Word Pattern - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


 

문제

문자열과 패턴이 주어졌을 때 패턴과 일치하는 문자열이면 true를 리턴

Ex) Input: pattern = "abba", s = "dog cat cat dog"  Output: true

 

어떻게 풀까

 ' '를 기준으로 split을 하여 문자열을 나눈다.

Pattern을 포문돌리며 character 를 한개씩 읽는다.

캐릭터를 키로 두고 hashmap에 값을 넣는다.

 

구현

 

class Solution {
    public boolean wordPattern(String pattern, String s) {
        String[] str = s.split(" ");
        HashMap<Character, String> hm = new HashMap<>();
        if (pattern.length() != str.length) return false;

        for(int i=0; i<pattern.length(); i++) {
            char c = pattern.charAt(i);
            if (hm.containsKey(c)) {
                String value = hm.get(c);
                if (!str[i].equals(value)) return false;
            } else {
                if (hm.containsValue(str[i])) return false;
                hm.put(c, str[i]);
            }
        }
        return true;

    }
}
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함