FTPrep, 76 Minimum Window Substring

来源:互联网 发布:phpstorm php配置 编辑:程序博客网 时间:2024/05/22 15:19

这道题绝对值得深入分析和总结相关的 substring的题型,个人感觉这类题虽然不是 intuitive,有点棘手,但是应该在面试还是经常可能出现的一类题。

TODO!!分析此题,总结该类题型。

代码:

class Solution {    public String minWindow(String s, String t) {        if(s.length()==0 || s.length()<t.length()) return "";        HashMap<Character, Integer> map= new HashMap<>();        for(int i=0; i<t.length(); i++){            if(map.containsKey(t.charAt(i))) map.put(t.charAt(i), map.get(t.charAt(i))+1);            else map.put(t.charAt(i), 1);        }        int left=0;        int matchCount=0;        int minLen=s.length()+1;        int minStart=0;        for(int right=0; right<s.length(); right++){            if(map.containsKey(s.charAt(right))){                map.put(s.charAt(right), map.get(s.charAt(right))-1);                if(map.get(s.charAt(right))>=0) matchCount++;                while(matchCount==t.length()){                    if(right-left+1<minLen){  // updating 2 things, so cannot write in tenary, both param are asscocaited min fragment                        minLen=right-left+1;                        minStart=left;                    }                    if(map.containsKey(s.charAt(left))){                        map.put(s.charAt(left), map.get(s.charAt(left))+1);                        if(map.get(s.charAt(left))>0) matchCount--;                    }                    left++;                }            }        }        if(minLen>s.length()) return "";        return s.substring(minStart, minStart+minLen);    }}// this solution is decent, but not the optimal, check the finish time status// more importantly, there is a template for this type of substring problem, should spend time on concluding them!!!


原创粉丝点击