Easy to understand by using stack(Java code)


  • 0
    X
    public boolean isValid(String s) {
        if (s == "")
        	return true;
        
        if (s.length() % 2 == 1)
        	return false;
        
        List<Character> stackList = new ArrayList<>();
        stackList.add(s.charAt(0));
        for (int i = 1; i < s.length(); i++) {
    		char currentChar = s.charAt(i);
    		int stackSize = stackList.size() - 1;
    		if (currentChar == '}' && 
    				stackList.get(stackSize) == '{') {
    			stackList.remove(stackSize);
    			continue;
    		}
    		
    		if (currentChar == ')' && 
    				stackList.get(stackSize) == '(') {
    			stackList.remove(stackSize);
    			continue;
    		}
    		
    		if (currentChar == ']' && 
    				stackList.get(stackSize) == '[') {
    			stackList.remove(stackSize);
    			continue;
    		}
    		
    		stackList.add(currentChar);
    	}
    	
    	return stackList.size() == 0 ? true : false;
    }

Log in to reply
 

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