Algorithm/LeetCode

[LeetCode]567. Permutation in String

Eric_Park 2021. 9. 26. 21:16

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.

 

from collections import Counter
class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        d1 = Counter(s1)
        k = len(s1)
        for i in range(len(s2)):  # ---- O(n)
            sub = s2[i:i + k]  # ------ O(k)
            d2 = Counter(sub)  # --- O(k)
            if d1 == d2:
                return True
        return False

#memo

아래는 time limit exceed 난 코드, 위 코드와 다른점은 

import Counter 를 사용하지 않고, list comprehension 으로 anagram 의 zip 을 만들었다. 

구조적으로 왜 속도 차이가 나는지는.. 좀 더 조사가 필요하다.. 

 


class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:

      flag = False
      len_s1 = len(s1)
      dict_s1 = dict(zip(s1, [s1.count(i) for i in s1]))
      for i in range(len(s2) - len(s1)+1):
          A = s2[i:i+len_s1]
          dict_A = dict(zip(A, [A.count(i) for i in A]))
          print(A)
          if dict_s1 == dict_A:
              print('s2를 탐색한 window와 s1의 dict구조 anagram 이 일치함')
              flag = True
              break
      return flag