子字符串模板 (双指针, 滑动窗口)

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

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循环内更​​新最小。

猜你喜欢

转载自www.cnblogs.com/willwuss/p/12276116.html
今日推荐