[LeetCode/Kotlin]Easy - 290. Word Pattern

2023. 6. 5. 21:55LeetCode/Kotlin | Easy

728x90
반응형
 

Word Pattern - LeetCode

Can you solve this real interview question? Word Pattern - 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

leetcode.com

문제

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 ' '.
  • 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
    }
}
728x90
반응형