###### tags: `Week_2`, `Sliding Window` # Sliding Window ## 438. [Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) Beny ```csharp= public class Solution { public IList<int> FindAnagrams(string s, string p) { var ans = new List<int>(); var sm = new int[26]; var pm = new int[26]; int i = 0, j = 0;//i為視窗開始位置 j為視窗尾巴位置 if(p.Length > s.Length) return ans;//長度不對返回空的 for(; i<p.Length; ++i){//設定一開始的window pm[p[i] - 'a']++; sm[s[i] - 'a']++; } for(; i<s.Length; ++i){ if(Enumerable.SequenceEqual(sm, pm)) ans.Add(j);// 比較兩者是否相等 相等的話加入 sm[s[i] - 'a']++; //在該字母欄位增加1 為加入的字元 sm[s[j] - 'a']--; //在該字母欄位減少1 移除最前面的字元 j++; //視窗開始的位置 } if(Enumerable.SequenceEqual(sm, pm)) ans.Add(j);//上面FOR少跑最後一次補上去 return ans; } } ``` ## 424. [ Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/submissions/) Beny ```csharp= public class Solution { public int CharacterReplacement(string s, int k) { int[] sm = new int[26]; //題目為 A-Z 所以設定為26 int start = 0, end = 0, maxCount = 0, maxLength = 0; // 類似two point 起始 結束 可以抵銷掉是重複的字元最大值 字串最大長度 for(;end < s.Length; end ++){ maxCount = Math.Max(maxCount, ++ sm[s[end] - 'A']); //若是重複的字元就在該地方+1 if(end - start + 1 - maxCount > k){ //當視窗-可扣重複字元還是大於K時 清除一開始的重複字元 並將起始向後移一格 sm[s[start]-'A'] --; start ++; } maxLength = Math.Max(maxLength, end - start +1); //計算最大字串長度 } return maxLength; } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up