zoukankan      html  css  js  c++  java
  • 子字符串模板 (双指针, 滑动窗口)

      对于大多数子字符串问题,我们给了一个字符串,需要找到一个满足某些限制的子字符串。通常的方法是使用带有两个指针的哈希表。模板如下。

    public int findSubstring(string s){
            Map<Character, Integer> map = new HashMap<>():
            //也可用256长度的数组代替, int[] map = new int[256];
            int counter;                            // check whether the substring is valid
            int begin=0, end=0;                     //two pointers, one point to tail and one head
            int subLength;                          //the length of substring
    
            for() { 
                /* initialize the hash map here */ 
            }
    
            while (end < s.size()) {
    
                if (map[s[end++]]-- ?) {  
                    /* modify counter here */ 
                }
    
                while (/* counter condition */) { 
                     
                     /* update subLength here if finding minimum*/
    
                    //increase begin to make it invalid/valid again
                    
                    if (map[s[begin++]]++ ?) { 
                        /*modify counter here*/ 
                    }
                }  
    
                /* update subLength here if finding maximum*/
            }
            return subLength;
      }
    

      需要提到的一件事是,当要求找到最大子串时,我们应该在内部while循环之后更新最大值,以确保子串有效。另一方面,当要求找到最小子串时,我们应该在内部while循环内更​​新最小。

  • 相关阅读:
    day5 元组、列表、字典和集合
    day4 字符串类型和列表类型的详细caozu
    day3 数据类型
    预习
    python基础
    计算机基础——老年人上网冲浪手册
    pycharm操作指北
    day1 计算机基础知识
    Securing a Laravel API in 20 minutes with JWTs
    Testing Api using PHPUnit Laravel
  • 原文地址:https://www.cnblogs.com/willwuss/p/12276116.html
Copyright © 2011-2022 走看看