LeetCode in Kotlin

567. Permutation in String

Medium

Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.

In other words, return true if one of s1’s permutations is the substring of s2.

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:

Solution

class Solution {
    fun checkInclusion(s1: String, s2: String): Boolean {
        val n = s1.length
        val m = s2.length
        if (n > m) {
            return false
        }
        val cntS1 = IntArray(26)
        val cntS2 = IntArray(26)
        for (i in 0 until n) {
            cntS1[s1[i].code - 'a'.code]++
        }
        for (i in 0 until n) {
            cntS2[s2[i].code - 'a'.code]++
        }
        if (check(cntS1, cntS2)) {
            return true
        }
        for (i in n until m) {
            cntS2[s2[i - n].code - 'a'.code]--
            cntS2[s2[i].code - 'a'.code]++
            if (check(cntS1, cntS2)) {
                return true
            }
        }
        return false
    }

    private fun check(cnt1: IntArray, cnt2: IntArray): Boolean {
        for (i in 0..25) {
            if (cnt1[i] != cnt2[i]) {
                return false
            }
        }
        return true
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy