본문 바로가기
  • Jetpack 알아보기
LeetCode/Easy

[Java] LeetCode 290 : Word Pattern

by 새우버거♬ 2021. 4. 17.

LeetCode # 290


 

Example 1:

 

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

 

Note:

  • 1 <= pattern.length <= 300
  • pattern contains only lower-case English letters.
  • 1 <= s.length <= 3000
  • s contains only lower-case English letters and spaces ' '.
  • does not contain any leading or trailing spaces.
  • All the words in s are separated by a single space.

 


Solution #1 (1ms)

class Solution {
    public boolean wordPattern(String pattern, String s) {
        Map<Character, String> map_char = new HashMap<>(); // <a, dog>, <b, cat>, <c, fish>
        Map<String, Character> map_str = new HashMap<>(); // <dog, a>, <cat, b>, <fish, c>
        String[] array = s.split(" ");

        if (pattern.length() != array.length) return false;

        for (int i = 0; i < pattern.length(); i++) {
            char c = pattern.charAt(i);
            String str = array[i];
            if (map_char.get(c) == null) { // Map에 'a', 'b'. 'c'.. 의 값이 없을 경우
                if (map_str.containsKey(str)) {
                    return false;
                } else {
                    map_char.put(c, str);
                    map_str.put(str, c);
                }
            } else {
                if (!map_char.get(c).equals(str)) {
                    return false;
                }
            }
        }

        return true;
    }
}

 

Result #1

 


 

More Algorithm!

 

👇👇

 

github.com/ggujangi/ggu.leet-code

 

ggujangi/ggu.leet-code

LeetCode, Java. Contribute to ggujangi/ggu.leet-code development by creating an account on GitHub.

github.com

 

 

 

 

출처 : leetCode