문제
Given a pattern and a string s, find if s follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
Example 1:
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Example 2:
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false
Constraints:
- 1 <= pattern.length <= 300
- pattern contains only lower-case English letters.
- 1 <= s.length <= 3000
- s contains only lowercase English letters and spaces ' '.
- s does not contain any leading or trailing spaces.
- All the words in s are separated by a single space.
풀이
나의 풀이법
풀이 접근 과정
Kotlin 함수를 사용하고 싶어서 두개의 배열을 합치는 법을 찾아봤는데 Zip 함수가 나왔다.
이걸 쓰니 해결되긴 했지만, 그래서 더 돌아간 것도 있는 것 같다.
최종 소스코드
class Solution {
fun wordPattern(pattern: String, s: String): Boolean {
val map1 = mutableMapOf<String, String>()
val map2 = mutableMapOf<String, String>()
val patterns = pattern.split("").slice(1..pattern.length)
val sArray = s.split(" ")
if (patterns.size != sArray.size) return false
patterns.zip(sArray) { i1, i2 ->
if (map1[i1].isNullOrEmpty()) map1[i1] = i2
else if (map1[i1] != i2) return false
if (map2[i2].isNullOrEmpty()) map2[i2] = i1
else if (map2[i2] != i1) return false
if (map1[map2[i2]] != i2) return false
}
return true
}
}
'LeetCode > Kotlin | Easy' 카테고리의 다른 글
[LeetCode/Kotlin]Easy - 66. Plus One (0) | 2023.06.10 |
---|---|
[LeetCode/Kotlin]Easy - 9. Palindrome Number (0) | 2023.06.10 |
[LeetCode/Kotlin]Easy - 1470. Shuffle the Array (0) | 2023.06.05 |
[LeetCode/Kotlin]Easy - 14. Longest Common Prefix (0) | 2023.05.29 |
[LeetCode/Kotlin]Easy - 118. Pascal's Triangle (0) | 2023.05.29 |