您的位置:首页 > 其它

leetcode---Valid Parentheses

2016-06-21 10:32 405 查看
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.

解题思路:使用一个栈临时存储,这样就可以比较相邻的元素。

package stringTest;

import java.util.Stack;

public class isValiad {

public static boolean isValid(String s) {
if (s.length() == 0 || s.equals(""))
return false;
char[] c = s.toCharArray();
if (c.length == 1)
return false;
int n = s.length();
Stack<Character> sta = new Stack<Character>();

for (int i = 0; i < n; i++) {
if (sta.isEmpty()) {
sta.push(c[i]);
} else {
if ((c[i] == ')' && sta.peek() == '(')
|| (c[i] == '}' && sta.peek() == '{')
|| (c[i] == ']' && sta.peek() == '[')) {
sta.pop();
continue;
} else {
sta.push(c[i]);
}
}
}
return sta.isEmpty();
}

public static void main(String[] args) {
String s = "[]()";
System.out.print(isValid(s));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string stack