【leetcode】Valid Parentheses(easy)


Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.


最近想熟练用java,就先从字符串处理相关的题目开始做起。

用一个栈即可。

public static boolean isValid(String s) {
		Stack<Character> stack = new Stack<Character>();
	    for(int i=0;i<s.length();i++){
	    	char t = s.charAt(i);
	    	if (t=='(' || t=='{' || t=='['){
	    		stack.push(t);
	    	}
	    	else{
	    		if (stack.empty())
	    			return false;
	    		char p = (char)stack.peek();
    			if ((p == '(' && t == ')' ) || (p == '[' && t == ']') || (p == '{' && t == '}')){
    				stack.pop();
    			}
    			else{
    				return false;
    			}
	    	}
	    }
		return stack.empty();
	}


你可能感兴趣的:(【leetcode】Valid Parentheses(easy))