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 ' '.
- s 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
출처 : leetCode
'LeetCode > Easy' 카테고리의 다른 글
[Java] LeetCode 874 : Walking Robot Simulation (0) | 2021.04.17 |
---|---|
[Java] LeetCode 1518 : Water Bottles (0) | 2021.04.17 |
[Java] LeetCode 914 : X of a Kind in a Deck of Cards (0) | 2021.04.17 |
[Java] LeetCode 1486 : XOR Operation in an Array (0) | 2021.04.17 |
[Java] LeetCode 977 : Squares of a Sorted Array (0) | 2021.03.30 |