|
43 | 43 |
|
44 | 44 | <!-- 这里可写通用的实现逻辑 -->
|
45 | 45 |
|
| 46 | +维护一个长度固定的窗口向前滑动 |
| 47 | + |
46 | 48 | <!-- tabs:start -->
|
47 | 49 |
|
48 | 50 | ### **Python3**
|
49 | 51 |
|
50 | 52 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
51 | 53 |
|
52 | 54 | ```python
|
53 |
| - |
| 55 | +class Solution: |
| 56 | + def checkInclusion(self, s1: str, s2: str) -> bool: |
| 57 | + n1, n2 = len(s1), len(s2) |
| 58 | + if n1 > n2: |
| 59 | + return False |
| 60 | + window = [0 for _ in range(26)] |
| 61 | + for i in range(n1): |
| 62 | + window[ord(s1[i]) - ord('a')] += 1 |
| 63 | + window[ord(s2[i]) - ord('a')] -= 1 |
| 64 | + if self.check(window): return True |
| 65 | + for i in range(n1, n2): |
| 66 | + window[ord(s2[i]) - ord('a')] -= 1 |
| 67 | + window[ord(s2[i - n1]) - ord('a')] += 1 |
| 68 | + if self.check(window): return True |
| 69 | + return False |
| 70 | + |
| 71 | + def check(self, window: List[int]) -> bool: |
| 72 | + return all([cnt == 0 for cnt in window]) |
54 | 73 | ```
|
55 | 74 |
|
56 | 75 | ### **Java**
|
57 | 76 |
|
58 | 77 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
59 | 78 |
|
60 | 79 | ```java
|
| 80 | +class Solution { |
| 81 | + public boolean checkInclusion(String s1, String s2) { |
| 82 | + int n1 = s1.length(), n2 = s2.length(); |
| 83 | + if (n1 > n2) { |
| 84 | + return false; |
| 85 | + } |
| 86 | + int[] window = new int[26]; |
| 87 | + for (int i = 0; i < n1; i++) { |
| 88 | + window[s1.charAt(i) - 'a']++; |
| 89 | + window[s2.charAt(i) - 'a']--; |
| 90 | + } |
| 91 | + if (check(window)) { |
| 92 | + return true; |
| 93 | + } |
| 94 | + for (int i = n1; i < n2; i++) { |
| 95 | + window[s2.charAt(i) - 'a']--; |
| 96 | + window[s2.charAt(i - n1) - 'a']++; |
| 97 | + if (check(window)) { |
| 98 | + return true; |
| 99 | + } |
| 100 | + } |
| 101 | + return false; |
| 102 | + } |
| 103 | + |
| 104 | + private boolean check(int[] window) { |
| 105 | + return Arrays.stream(window).allMatch(cnt -> cnt == 0); |
| 106 | + } |
| 107 | +} |
| 108 | +``` |
61 | 109 |
|
| 110 | +### **Go** |
| 111 | + |
| 112 | +```go |
| 113 | +func checkInclusion(s1 string, s2 string) bool { |
| 114 | + n1, n2 := len(s1), len(s2) |
| 115 | + if n1 > n2 { |
| 116 | + return false |
| 117 | + } |
| 118 | + window := make([]int, 26) |
| 119 | + for i := 0; i < n1; i++ { |
| 120 | + window[s1[i]-'a']++ |
| 121 | + window[s2[i]-'a']-- |
| 122 | + } |
| 123 | + if check(window) { |
| 124 | + return true |
| 125 | + } |
| 126 | + for i := n1; i < n2; i++ { |
| 127 | + window[s2[i]-'a']-- |
| 128 | + window[s2[i-n1]-'a']++ |
| 129 | + if check(window) { |
| 130 | + return true |
| 131 | + } |
| 132 | + } |
| 133 | + return false |
| 134 | +} |
| 135 | + |
| 136 | +func check(window []int) bool { |
| 137 | + for _, cnt := range window { |
| 138 | + if cnt != 0 { |
| 139 | + return false |
| 140 | + } |
| 141 | + } |
| 142 | + return true |
| 143 | +} |
62 | 144 | ```
|
63 | 145 |
|
64 | 146 | ### **...**
|
|
0 commit comments