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

Posted coding-gaga

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[程序员代码面试指南]字符串问题-找到包含串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;
    

以上是关于[程序员代码面试指南]字符串问题-找到包含串b所有字符的最小子串的主要内容,如果未能解决你的问题,请参考以下文章

[程序员代码面试指南]递归和动态规划-最长公共子串问题

[程序员代码面试指南]字符串问题-回文最少分割数(DP)

[程序员代码面试指南]数组和矩阵问题-找到无序数组中最小的k个数(堆排序)

《程序员代码面试指南》第八章 数组和矩阵问题 找到无序数组中最小的k 个数

[程序员代码面试指南]二叉树问题-树1是否包含树2的拓扑结构

《程序员代码面试指南》第八章 数组和矩阵问题 不包含本位置值的累乘数组