雙指針算法專題(二)之滑動窗口

1.leetcode3 無重複字符的最長子串

給定一個字符串,請你找出其中不含有重複字符的 最長子串 的長度。

示例 1:

輸入: "abcabcbb"
輸出: 3 
解釋: 因爲無重複字符的最長子串是 "abc",所以其長度爲 3。

示例 2:

輸入: "bbbbb"
輸出: 1
解釋: 因爲無重複字符的最長子串是 "b",所以其長度爲 1。

示例 3:

輸入: "pwwkew"
輸出: 3
解釋: 因爲無重複字符的最長子串是 "wke",所以其長度爲 3。
     請注意,你的答案必須是 子串 的長度,"pwke" 是一個子序列,不是子串。

 

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int len=s.length();
        int ans=0,i=0,j=0;
        Set<Character>chs=new HashSet<>();
        while(j<len){
            if(!chs.contains(s.charAt(j))){//如果右邊界不重複
                ans=Math.max(ans,j-i+1);//尋找最大值
                chs.add(s.charAt(j++));//把右邊界加入chs同時右移
            }
            else{//右邊界重複
                chs.remove(s.charAt(i++));//移除左邊界同時左邊界左移
            }
        }
        return ans;
    }
}

2. leetcode1004 最大連續1的個數 III

給定一個由若干 01 組成的數組 A,我們最多可以將 K 個值從 0 變成 1 。

返回僅包含 1 的最長(連續)子數組的長度。

 

示例 1:

輸入:A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
輸出:6
解釋: 
[1,1,1,0,0,1,1,1,1,1,1]
粗體數字從 0 翻轉到 1,最長的子數組長度爲 6。

示例 2:

輸入:A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
輸出:10
解釋:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
粗體數字從 0 翻轉到 1,最長的子數組長度爲 10。

 

提示:

  1. 1 <= A.length <= 20000
  2. 0 <= K <= A.length
  3. A[i] 爲 0 或 1 
class Solution {
    public int longestOnes(int[] A, int K) {
        int left=0;
        int right=0;
        int len=A.length;
        int ans=0;
        int cnt=0;
        while(right<len){
            if(A[right]==0){//如果右邊界爲0,則翻轉爲1同時cnt+1
                cnt++;
            }
            while(cnt>K){//cnt大於最大翻轉機會,左邊界左移至cnt<=k
                if(A[left]==0)
                    cnt--;
                left++;
            }
            ans=Math.max(ans,right-left+1);//求出最大值
            right++;
        }
        return ans;
        
    }
    
}

3.

給定兩個字符串 s1 和 s2,寫一個函數來判斷 s2 是否包含 s1 的排列。

換句話說,第一個字符串的排列之一是第二個字符串的子串。

示例1:

輸入: s1 = "ab" s2 = "eidbaooo"
輸出: True
解釋: s2 包含 s1 的排列之一 ("ba").

 

示例2:

輸入: s1= "ab" s2 = "eidboaoo"
輸出: False

 

class Solution {
    public boolean checkInclusion(String s1, String s2) {
        //滑動窗口
       int l1=s1.length();
       int l2=s2.length();
       int []hash1=new int[26];
       int []hash2=new int[26];
        for(char c:s1.toCharArray()){
            hash1[c-'a']++;
        }
       int i=0,j=0;
        while(j<l2){
            if(j-i+1>l1){
                hash2[s2.charAt(i)-'a']--;
                i++;
            }
            else{
                hash2[s2.charAt(j)-'a']++;
                j++;
                if(Arrays.equals(hash1,hash2))
                    return true;
            }
            
            
        }
        return false;
       
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章