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

   对于字符串窗口的问题,使用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.
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值