Can anyone help me to modify my code (TLE) to get accepted? Thanks!


  • 0
    public String minWindow(String S, String T) {
    String result = "";
    if(S.length()==0||S==null||T.length()==0||T==null)return result;
    Map<Character, Integer> mapT = new HashMap<Character, Integer>();
    for(int i = 0; i < T.length(); i++){
        if(!mapT.containsKey(T.charAt(i))){
            mapT.put(T.charAt(i), 1);
        }else{
            mapT.put(T.charAt(i), 1 + mapT.get(T.charAt(i)));
        }
    }
    int i = 0, index = 0, length = Integer.MAX_VALUE;
    for(int start = 0; start < S.length() - T.length() + 1; start++){
    	if(!mapT.containsKey(S.charAt(start))) continue;
        Map<Character, Integer> mapSubWin = new HashMap<Character, Integer>();
        for(i = start; i < S.length(); i++){
            if(mapT.containsKey(S.charAt(i))){
                if(mapSubWin.containsKey(S.charAt(i)))
                    mapSubWin.put(S.charAt(i), 1+mapSubWin.get(S.charAt(i)));
                else
                    mapSubWin.put(S.charAt(i), 1);
            }                
            if(mapT.equals(mapSubWin)){
                if((i - start + 1) < length){
                    length = i - start + 1;
                    index = start;
                }
                break;
            }                
        }
    
    }
    if(length < S.length()) 
        result =  S.substring(index, index + length);
    return result;
    

    }

    It can run in IDE, but got TLE...Thanks a lot!!


  • 0
    Z

    Would you like to add some comments/explanations?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.