|
| 1 | +""" |
| 2 | +Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string. |
| 3 | +Example 1: |
| 4 | +Input:s1 = "ab" s2 = "eidbaooo" |
| 5 | +Output:True |
| 6 | +Explanation: s2 contains one permutation of s1 ("ba"). |
| 7 | +Example 2: |
| 8 | +Input:s1= "ab" s2 = "eidboaoo" |
| 9 | +Output: False |
| 10 | +Note: |
| 11 | +The input strings only contain lower case letters. |
| 12 | +The length of both given strings is in range [1, 10,000]. |
| 13 | + |
| 14 | +类似于 Find All Anagrams in a String 难度应该颠倒过来。 |
| 15 | + |
| 16 | +这个的测试用例更丰富,发现了没想到的一个盲点。 |
| 17 | + |
| 18 | +思路请看 https://github.com/HuberTRoy/leetCode/blob/master/DP/FindAllAnagramsInAString.py |
| 19 | + |
| 20 | + |
| 21 | +beat 79% |
| 22 | + |
| 23 | +测试地址: |
| 24 | +https://leetcode.com/problems/permutation-in-string/description/ |
| 25 | + |
| 26 | + |
| 27 | +""" |
| 28 | +class Solution(object): |
| 29 | + def checkInclusion(self, s1, s2): |
| 30 | + """ |
| 31 | + :type s1: str |
| 32 | + :type s2: str |
| 33 | + :rtype: bool |
| 34 | + """ |
| 35 | + if len(s1) > len(s2): |
| 36 | + return False |
| 37 | + |
| 38 | + counts = {} |
| 39 | + |
| 40 | + for i in s1: |
| 41 | + try: |
| 42 | + counts[i] += 1 |
| 43 | + except: |
| 44 | + counts[i] = 1 |
| 45 | + |
| 46 | + pre = counts.copy() |
| 47 | + |
| 48 | + for c in range(len(s2)): |
| 49 | + i = s2[c] |
| 50 | + if i in pre: |
| 51 | + pre[i] -= 1 |
| 52 | + if not pre[i]: |
| 53 | + pre.pop(i) |
| 54 | + |
| 55 | + if not pre: |
| 56 | + return True |
| 57 | + else: |
| 58 | + if i in counts: |
| 59 | + if i != s2[c-len(s1)+sum(pre.values())]: |
| 60 | + for t in s2[c-len(s1)+sum(pre.values()):c]: |
| 61 | + if t == i: |
| 62 | + break |
| 63 | + try: |
| 64 | + pre[t] += 1 |
| 65 | + except: |
| 66 | + pre[t] = 1 |
| 67 | + continue |
| 68 | + pre = counts.copy() |
| 69 | + if i in pre: |
| 70 | + pre[i] -= 1 |
| 71 | + if not pre[i]: |
| 72 | + pre.pop(i) |
| 73 | + |
| 74 | + return False |
0 commit comments