zoukankan      html  css  js  c++  java
  • [程序员代码面试指南]字符串问题-最小包含子串的长度

    题意

    给串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;
    	}
    }
    
  • 相关阅读:
    cf 1452E. Two Editorials(中点排序)
    cf 888G
    cf 1447E. Xor Tree(二进制分治)
    2020ICPC·小米 网络选拔赛第一场 E-Phone Network (线段树)
    cf 1447D. Catching Cheaters ( 最大子段和思想 dp )
    POJ
    cf 1437F.Emotional Fishermen(计数dp)
    霍夫丁不等式
    切比雪夫不等式
    霍夫丁不等式引理证明
  • 原文地址:https://www.cnblogs.com/coding-gaga/p/11020515.html
Copyright © 2011-2022 走看看