题目链接:https://leetcode.com/problems/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.
解题思路:
括号匹配典型的思路就是利用栈。
- 遇到左括号进栈,遇到右括号就弹出栈顶。
- 如果栈为空或者栈顶不是右括号对应的左括号,返回 false。
- 扫描完全部括号后判断栈是否为空,不为空(剩余的左括号没有遇到和它匹配的右括号)返回 false。
public class Solution {
public boolean isValid(String s) {
if(s == null || s.length() == 0)
return false;
LinkedList<Character> list = new LinkedList();
HashMap<Character, Character> map = new HashMap();
map.put('(', ')');
map.put('{', '}');
map.put('[', ']');
for(int i = 0; i < s.length(); i ++) {
char c = s.charAt(i);
if(c == '(' || c == '{' || c == '[')
list.push(c);
else {
if(list.isEmpty() || c != map.get(list.pop()))
return false;
}
}
if(list.isEmpty())
return true;
else
return false;
}
}
65 / 65 test cases passed.
Status: Accepted
Runtime: 296 ms