File tree 1 file changed +43
-36
lines changed
1 file changed +43
-36
lines changed Original file line number Diff line number Diff line change @@ -112,42 +112,49 @@ func minWindow(s string, t string) string {
112
112
> 给定两个字符串 ** s1** 和 ** s2** ,写一个函数来判断 ** s2** 是否包含 \*\* s1 \*\* 的排列。
113
113
114
114
``` go
115
- func checkInclusion (s1 string , s2 string ) bool {
116
- win := make (map [byte ]int )
117
- need := make (map [byte ]int )
118
- for i := 0 ; i < len (s1); i++ {
119
- need[s1[i]]++
120
- }
121
- left := 0
122
- right := 0
123
- match := 0
124
- for right < len (s2) {
125
- c := s2[right]
126
- right++
127
- if need[c] != 0 {
128
- win[c]++
129
- if win[c] == need[c] {
130
- match++
131
- }
132
- }
133
- // 当窗口长度大于字符串长度,缩紧窗口
134
- for right-left >= len (s1) {
135
- // 当窗口长度和字符串匹配,并且里面每个字符数量也匹配时,满足条件
136
- if match == len (need) {
137
- return true
138
- }
139
- d := s2[left]
140
- left++
141
- if need[d] != 0 {
142
- if win[d] == need[d] {
143
- match--
144
- }
145
- win[d]--
146
- }
147
- }
148
- }
149
- return false
150
- }
115
+ class Solution {
116
+ public:
117
+ bool checkInclusion (string s1, string s2) {
118
+
119
+ if (s1.size ()>s2.size ())
120
+ return false ;
121
+
122
+ vector<int > s1_map (26 , 0 );
123
+ vector<int > s2_map (26 , 0 );
124
+
125
+ for (int i=0 ; i< s1.size (); i++)
126
+ s1_map[s1[i]-' a' ]++;
127
+
128
+ int count =0 ;
129
+ for (int i=0 ; i< s1.size (); i++)
130
+ {
131
+ int index = s2[i] - ' a' ;
132
+ s2_map[index]++;
133
+ if (s2_map[index]<=s1_map[index])
134
+ count++;
135
+ }
136
+ if (count == s1.size ())
137
+ return true ;
138
+
139
+ for (int i= s1.size (); i< s2.size (); i++)
140
+ {
141
+ int index = s2[i] - ' a' ;
142
+ s2_map[index]++;
143
+ if (s2_map[index]<=s1_map[index])
144
+ count++;
145
+ index = s2[i-s1.size ()] - ' a' ;
146
+ s2_map[index]--;
147
+ if (s2_map[index]<s1_map[index])
148
+ count--;
149
+
150
+ if (count == s1.size ())
151
+ return true ;
152
+ }
153
+
154
+ return false ;
155
+
156
+ }
157
+ };
151
158
```
152
159
153
160
[ find-all-anagrams-in-a-string] ( https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/ )
You can’t perform that action at this time.
0 commit comments