LeetCode 0567. Permutation in String Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0567. Permutation in String

Description

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:

  • 1 <= s1.length, s2.length <= 104
  • s1 and s2 consist of lowercase English letters.

Solutions

Solution 1: Sliding Window

We use an array cnt to record the characters and their counts that need to be matched, and a variable need to record the number of different characters that still need to be matched. Initially, cnt contains the character counts from the string s1, and need is the number of different characters in s1.

Then we traverse the string s2. For each character, we decrement its corresponding value in cnt. If the decremented value equals 0, it means the current character's count in s1 is satisfied, and we decrement need. If the current index i is greater than or equal to the length of s1, we need to increment the corresponding value in cnt for s2[i-s1]. If the incremented value equals 1, it means the current character's count in s1 is no longer satisfied, and we increment need. During the traversal, if the value of need equals 0, it means all character counts are satisfied, and we have found a valid substring, so we return true.

Otherwise, if the traversal ends without finding a valid substring, we return false.

The time complexity is O(m + n), where m and n are the lengths of strings s1 and s2, respectively. The space complexity is O(|Σ|), where Σ is the character set. In this problem, the character set is lowercase letters, so the space complexity is constant.

PythonJavaC++GoTypeScriptRustC#PHP
class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: cnt = Counter(s1) need = len(cnt) m = len(s1) for i, c in enumerate(s2): cnt[c] -= 1 if cnt[c] == 0: need -= 1 if i >= m: cnt[s2[i - m]] += 1 if cnt[s2[i - m]] == 1: need += 1 if need == 0: return True return False(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !