[程序员代码面试指南]字符串问题-找到包含串b所有字符的最小子串

题意

给串A和串B,找到A包含B所有出现字符(相同字符出现几次就要包含几次)的最小子串,输出子串长度

题解

维护一个窗口作为当前考察子串,使用一个hashmap记录每个字符在当前子串已出现情况。时间复杂度O(n).

代码

import java.util.HashMap;

public class Main {
    public static void main(String args[]) {
        //test
        Node root=new Node(1);
        Node n1=new Node(-1);
        Node n2=new Node(2);
        Node n3=new Node(-3);
        root.left=n1;
        root.right=n2;
        n2.left=n3;
        int targetVal=0;
        
        HashMap<Integer,Integer> sumMap=new HashMap<>();
        sumMap.put(0, 0);
        int maxLen=preOrder(root,targetVal,1,0,0,sumMap);
        System.out.println(maxLen);
    }
    
    public static int preOrder(Node root,int targetVal,int level,int preSum,int maxLen,HashMap<Integer,Integer> sumMap) {
        if(root==null) {
            return maxLen;
        }
        int curSum=preSum+root.val;//累加和
        if(!sumMap.containsKey(curSum)) {//更新HashMap
            sumMap.put(curSum, level);
        }
        if(sumMap.containsKey(curSum-targetVal)) {//更新MaxLen
            maxLen=Math.max(maxLen, level-sumMap.get(curSum-targetVal));
        }
        maxLen=preOrder(root.left,targetVal,level+1,curSum,maxLen,sumMap);
        maxLen=preOrder(root.right,targetVal,level+1,curSum,maxLen,sumMap);
        if(sumMap.get(curSum)==level) {
            sumMap.remove(curSum);
        }
        return maxLen;
    }
}

猜你喜欢

转载自www.cnblogs.com/coding-gaga/p/11020515.html