LeetCode 字符串滑动窗口问题汇总:

本文汇总了LeetCode上四个与字符串滑动窗口相关的经典问题:1) 最小子字符串;2) 包含所有单词的字符串索引集合;3) 最长不重复字符的子串长度;4) 最长回文子串。针对每个问题,详细解释了题意并提供了题解思路,主要利用HashMap统计和动态规划方法来解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   对于字符串窗口的问题,使用hashmap来统计出现的字符及次数,然后通过构建窗口来统计,

 

1.最小子字符串(LeetCode: minimum-window-substring)

        Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).For example,      S ="ADOBECODEBANC"      T ="ABC"      Minimum window is"BANC".

Note:
         If there is no such window in S that covers all characters in T, return the emtpy string"".If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

       题意:给定一个字符串S和一个字符串T,找到S中的最小窗口,它将包含T中的所有字符,不要求顺序。

       题解:begin开始指向0, end一直后移,直到begin - end区间包含T中所有字符。如果长度小于min,更新字符串结果,然后begin开始后移,移除元素,直到移除的字符是T中的字符则停止,此时T中有一个字符没被包含在窗口,继续后移end,直到T中的所有字符被包含在窗口,重新更新结果,直到end到S中的最后一个字符。

import java.util.*;
public class Solution {
    public String minWindow(String S, String T) {
        int win =Integer.MAX_VALUE;
        String result ="";
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        for(int i =0;i<T.length();i++){
            char t =T.charAt(i);
            if(map.containsKey(t))
                map.put(t,map.get(t)+1);
            else
                map.put(t,1);
        }
        int len  = T.length();
        int start =0;
        int end = 0;
        while(end<S.length()){
            if(map.containsKey(S.charAt(end))){
                 map.put(S.charAt(end),map.get(S.charAt(end))-1);
                 if(map.get(S.charAt(end))>=0){
                    len--;
                }
            }
           while(len==0){
                if(end-start+1<win){
                    win = end-start+1;
                    result = S.substring(start,end+1);
                }
                if(map.containsKey(S.charAt(start))){
                      map.put(S.charAt(start),map.get(S.charAt(start))+1);
                      if(map.get(S.charAt(start))>0)
                          len++;
                }
                start++;
            }
            end++;
        }
        return result;
    }
}

 

2.包含所有单词的字符串索引集合:(LeetCode:substring-with-concatenation-of-all-words)

 

        You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

       For example, given:  S:"barfoothefoobarman"   L:["foo", "bar"]

       You should return the indices:[0,9].  (order does not matter).

      题意:一个字符串S和一个单词长度相同的单词列表L。 找到S中子串的所有起始索引,它是L中每个单词的串联,只有一次,且任何插入字符。

        题解:首先是先把所给的字典利用HashMap 进行统计,因为每个单词长度一样,外层循序只许循环wordLen次,每次指针挪一次,每一次循环遍历整个字符串。内层循环每次遍历一个单词 (即 j = j + wordLen),把整个S字符串遍历检查。需要在每次大循环维护一个count,看是不是达到了给的字典字符串数量,同时维护一个left 指针表示窗口的左端,也就是起始的index---每个符合条件的字符串的起始index,需要存到返回结果中。为了能够检查是不是合格字符串,在这里维护一个hasFind的HashMap。用于记录窗口内找到的单词及其数量。

import java.util.*;
public class Solution {
    public ArrayList<Integer> findSubstring(String S, String[] L) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        HashMap<String,Integer> map = new HashMap<String,Integer>();
        int start =0;
        int end = 0;
        int step = L[0].length();//长度;
        for(int i =0;i<L.length;i++){
            if(map.containsKey(L[i])){
                map.put(L[i],map.get(L[i])+1);
            }else{
                map.put(L[i],1);
            }
        }
        for(int i =0;i<step;i++){
            HashMap<String,Integer> m = new HashMap<String,Integer>();
            start = i;
            int count=0;
            for(int j = i;j+step<=S.length();j=j+step){
                String temp = S.substring(j,j+step);
                if(map.containsKey(temp)){
                    if(m.containsKey(temp)){
                        m.put(temp,m.get(temp)+1);
                    }else{
                        m.put(temp,1);
                    }
                    if(m.get(temp)<= map.get(temp)){
                        count++;
                    }else{
                        while(m.get(temp)> map.get(temp)){
                            String s = S.substring(start,start+step);
                            m.put(s,m.get(s)-1);
                            if(m.get(s)<map.get(s))
                                count--;//去掉了不重复的字符串
                            start = start+step;
                        }
                    }
                    if(count==L.length){
                        result.add(start);
                        String s = S.substring(start,start+step);
                        m.put(s,m.get(s)-1);
                        count--;
                        start += step;
                    }
                }else{
                    m.clear();
                    count=0;
                    start=j+step;
                }
            }
        }
        Collections.sort(result);
        return result;
    }
}

 

3.最长不重复字符的子串长度:(LeetCode:longest-substring-without-repeating-characters)

      Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

       题解:使用动态规划,f(i)表示以第i个字符结尾的最长不包含重复字符的子串的长度,如果第i个字符之前出现过,且与最后一次出现距离为dif,如果dif小于等于dp[i-1]表示出现位置在最长子串中,此时 dp[i] = dif,如果没有出现过,则的等于dp[i-1]+1。

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s.length()==0 || s==null)
            return 0;
        int len = s.length();
        int [] dp  = new int[len+1];
        dp[0]=1;
        int max =1;
        for(int i =1;i<len;i++){
            String temp = s.substring(0,i);
            int index = temp.lastIndexOf(s.charAt(i));
            if(index!=-1){
                int dif = i-index;
                if(dif<=dp[i-1])
                    dp[i] = dif;
                else 
                   dp[i] =dp[i-1]+1;
            }else{
                dp[i] = dp[i-1]+1;
            }
            max = Math.max(max,dp[i]);
        }
        return max;
    }
}

 

4. 最长回文子串:(LeetCode:longest-palindromic-substring)

       Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

       题解:遍历字符串,以字符串的该点为中心,向两边扩散,找到最长的回文子串,扩散寻找时,对以该点为中心的奇数回文串和偶数回文串分开判断。

import java.util.*;
public class Solution {
    public String longestPalindrome(String s) {
        //以该点为中心,向两边找以该点为中心的最长回文串
        if(s.length()==1)
            return s;
        int max = 1;
        String result = "";
        int index = 0;
        int start = 0;
        int count = 0;
        for(int i =0;i<s.length();i++){
            for(int j=0;(i-j)>=0 && (i+j)<s.length();j++){//奇数
                if(s.charAt(i-j)!=s.charAt(i+j))
                    break;
                index = j;
                count = 2*index+1;
            }
            if(max<count){
                max = count;
                start = i-index;
            }
            for(int j=0;(i-j)>=0 && (i+j+1)<s.length();j++){//偶数
                if(s.charAt(i-j)!=s.charAt(i+j+1))
                    break;
                index = j;
                count = 2*index+2;
            }
            if(max<count){
                max = count;
                start = i-index;
            }
        }
        result = s.substring(start,start+max);
        return result;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值