Valid Parentheses:括号匹配

来源:互联网 发布:2016中国网络视频报告 编辑:程序博客网 时间:2024/06/05 13:28

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.

思路:用个栈匹配即可,注意最后若栈不空则不是完全匹配的,同理,若中途栈已空但仍试图匹配括号时,也是不能完全匹配的。

class Solution {   public boolean isValid(String s) {Stack<Character> st = new Stack<Character>();for (int i = 0; i < s.length(); i++) {if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {st.push(s.charAt(i));}if (s.charAt(i) == ')') {try {char c = st.peek();if (c == '(') {st.pop();} else {return false;}} catch (Exception e) {return false;}}if (s.charAt(i) == ']') {try {char c = st.peek();if (c == '[') {st.pop();} else {return false;}} catch (Exception e) {return false;}}if (s.charAt(i) == '}') {try {char c = st.peek();if (c == '{') {st.pop();} else {return false;}} catch (Exception e) {return false;}}}if (st.isEmpty()){return true;} else {return false;}   }}

当然,代码不用这么长,因为只包含括号,所以可以这么写:

public boolean isValid(String s) {Stack<Character> stack = new Stack<Character>();for (char c : s.toCharArray()) {if (c == '(')stack.push(')');else if (c == '{')stack.push('}');else if (c == '[')stack.push(']');else if (stack.isEmpty() || stack.pop() != c)return false;}return stack.isEmpty();}
不够匹配或者不能匹配即返回FALSE,还是很省事的。

阅读全文
0 0
原创粉丝点击