1ms Java Solution using HashMap costs O(N) in time


  • 0
    Y
        if(s==null||s.length()%2!=0) return false;
    	HashMap<Integer,Character> map = new HashMap<Integer,Character>();
    	for(int i=0,j=-1;i<s.length();i++){
    	    if(s.charAt(i)=='('||s.charAt(i)=='['||s.charAt(i)=='{')
    	        map.put(++j,s.charAt(i));
    	    else if(s.charAt(i)==')'&&(!map.isEmpty())&&map.remove(j--)=='('){
    	        continue;
    	    }
    	    else if(s.charAt(i)=='}'&&(!map.isEmpty())&&map.remove(j--)=='{'){
    	        continue;
    	    }
    	    else if(s.charAt(i)==']'&&(!map.isEmpty())&&map.remove(j--)=='['){
    	        continue;
    	    }
    	    else
    	        return false;
    	}	
    	return map.isEmpty();

Log in to reply
 

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