티스토리 뷰
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; } }
'Algorithm > 릿코드(leetcode)' 카테고리의 다른 글
[릿코드] 167번 : Two Sum II - Input array is sorted (0) | 2021.05.10 |
---|---|
[릿코드] 35번 : Search Insert Position (0) | 2021.05.10 |
[릿코드] 204번 : Count Primes (0) | 2021.05.01 |
[릿코드] 1491번 : Average Salary Excluding the Minimum and Maximum Salary (0) | 2021.04.28 |
[릿코드] 999번 : Available Captures for Rook (0) | 2021.04.28 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 1491
- leetcode 35
- 2447
- ngrok
- elastic ip
- Docker
- leetcode 350
- LeetCode
- leetcode 349
- binarySearch
- Jenkins
- binary search
- 도커
- 백준
- java
- xmlpullparserexceptioin
- leetcode 69
- 뒤늦은 1년 후기
- 별찍기-10
- Github
- 언제까지할수있을까
- leetcode 167
- leetcode 204
- Leetcode717
- config.xml
- gradle빌드
- 릿코드
- leetcode 278
- 티스토리코드작성
- webhook
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함