20. Valid Parentheses
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.
思路:
Stack栈 的特点是后进先出,其中:
push() 将一个对象写入栈顶
peek() 方法返回栈顶对象且不将其出栈
pop() 返回栈顶对象并将其出栈
算法描述 :先判断字符串长度,为奇数一定不匹配,方法结束
为偶数用for循环遍历字符串每个字符,栈为空将当前字符入栈,做下一次循环;
栈不为空做比较,如果当前栈顶和当前位置字符是匹配的一对,pop方法出栈,不匹配当前字符就入栈;
循环结束栈为空,表示满足括号匹配
出栈的过程就是一次匹配的过程如果最后栈不为空 表示一定有括号没匹配。
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
if (s.length() % 2 == 1)
return false;
for (int i = 0; i < s.length(); i++) {
if (stack.isEmpty()) {
stack.push(s.charAt(i));
} else if(stack.peek()=='('&& s.charAt(i)==')'
|| stack.peek()=='['&& s.charAt(i)==']'
|| stack.peek()=='{'&& s.charAt(i)=='}'){
stack.pop();
}else{
stack.push(s.charAt(i));
}
}
if(stack.isEmpty())return true;
else return false;
}