My Java solution, can we make it better?


  • 6
    E
    public class Solution {
    public boolean isValid(String s) {
        Stack<Character> stk=new Stack();
    	for (int i=0;i<s.length();i++){
    		switch(s.charAt(i)){
    		case('{'): stk.push('{'); break;
    		case('('): stk.push('('); break;
    		case('['): stk.push('['); break;
    		case('}'): if (!stk.isEmpty() && stk.peek() == '{') {stk.pop(); break;} else return false;
    		case(')'): if (!stk.isEmpty() && stk.peek() == '(') {stk.pop(); break;} else return false;
    		case(']'): if (!stk.isEmpty() && stk.peek() == '[') {stk.pop(); break;} else return false;
    		default: break;
    		}
    	}
    	return stk.isEmpty();
    
    }
    

    }


Log in to reply
 

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