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;
    	}
    }
    
  • 相关阅读:
    Laravel 中查询 where 记录
    eclipse svn重定位(relocate)
    使用git ftp发布我个人的hexo博客内容
    oracle数据库查询常用语句
    telnet关闭tomcat
    XML字符串解析成对象的时候应注意空格
    去除焦点边框线
    如何查看和更改mysql数据库文件存放位置
    设置div,td失去焦点
    (加减乘除)字符串计算机
  • 原文地址:https://www.cnblogs.com/coding-gaga/p/11020515.html
Copyright © 2011-2022 走看看