Given two strings
In other words, return
Example 1:
Input: s1 = "ab", s2 = "eidbaooo" Output: true Explanation: s2 contains one permutation of s1 ("ba").
Example 2:
Input: s1 = "ab", s2 = "eidboaoo" Output: false
Constraints:
1 <= s1.length, s2.length <= 104 s1 ands2 consist of lowercase English letters.
Solution
要找 permutation 其實就是要把 s1 的每個字元都用到
所以在這題,只要改一下終止條件就可以
只要找到 subsstring 的長度和 s1 一樣,就可以回傳 true
如果沒找到,就回傳 false
kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun checkInclusion(s1: String, s2: String): Boolean { | |
val map = mutableMapOf<Char,Int>() | |
for(c in s1) { | |
map[c] = map[c]?.let { it + 1 } ?: 1 | |
} | |
var left = 0 | |
var cnt = 0 | |
for(right in s2.indices) { | |
if(map[s2[right]] != null) { | |
map[s2[right]] = map[s2[right]]!! - 1 | |
if(map[s2[right]]!! >= 0) { | |
++cnt | |
} | |
} | |
while(cnt == s1.length) { | |
if(right - left + 1 == s1.length) { | |
return true | |
} | |
if(map[s2[left]] != null) { | |
map[s2[left]] = map[s2[left]]!! + 1 | |
if(map[s2[left]]!! > 0) { | |
--cnt | |
} | |
} | |
++left | |
} | |
} | |
return false | |
} | |
} |
沒有留言:
張貼留言