您的位置:首页 > 其它

LeetCode 20. Valid Parentheses--验证括号是否有效

2017-08-25 12:17 726 查看
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.
import java.util.Stack;

public class Main {

public boolean isValid(String s) {
int n = s.length();
Stack<Character> stack = new Stack<Character>();
char[] c = s.toCharArray();
for (int i = 0; i < n; i++) {
if (c[i] == '(') {
stack.push(')');
} else if (c[i] == '[') {
stack.push(']');
} else if (c[i] == '{') {
stack.push('}');
} else if (stack.isEmpty() || stack.pop() != c[i]) {//pop是返回栈顶元素,并且删除栈顶元素
return false;
}
}//for
return stack.isEmpty();
}//isValid

public static void main(String[] args) {
//        System.out.println(new Main().isValid("{[()]}"));//true
System.out.println(new Main().isValid("{"));//false
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息