我如今在作一个叫《leetbook》的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,须要的同窗能够去看看
书的地址:https://hk029.gitbooks.io/leetbook/java
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.git
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.markdown
这道题很简单,就是一个经典的栈的例子——表达式中的括号符号匹配。
- 碰见了左括号就进栈
- 碰见了右括号就出栈
- 若是栈为空,出错
- 若是出栈元素不是匹配的括号,出错spa
这里解决出括号匹配用了一个小tick,就是利用ASCII码,匹配的括号的ascii码都不会相差太远
- ‘(’ ‘)’ 相差1
- ‘[’ ‘]’ ‘{’ ‘}’ 相差2code
public class Solution {
public boolean isValid(String s) {
if(s.length() == 0)
return false;
Stack<Character> stack = new Stack<Character>(); // 建立堆栈对象
for(int i = 0;i < s.length(); i++)
{
if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{')
stack.push(s.charAt(i));
if(s.charAt(i) == ')' || s.charAt(i) == ']' || s.charAt(i) == '}')
{
if(stack.empty()) return false;
char out = stack.pop();
if(out - s.charAt(i) > 2)
return false;
}
}
if(stack.empty())
return true;
return false;
}
}