LeetCode算法题-- 有效的括号
- 题目来源:https://leetcode-cn.com/problems/valid-parentheses/
题目要求
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: “()”
输出: true
示例 2:
输入: “()[]{}”
输出: true
示例 3:
输入: “()[]{}”
输出: true
示例 4:
输入: “([)]”
输出: false
示例 5:
输入: “{[]}”
输出: true
题目思路:
运用栈,迭代字符串,如果遇到开括号,压入栈中;遇到闭括号,若栈中有对应的开括号,弹出该开括号,继续迭代,若无,则false。
class Solution {
private HashMap<Character, Character> mapping;
public Solution(){
this.mapping = new HashMap<Character, Character>();
this.mapping.put(']','[');
this.mapping.put('}','{');
this.mapping.put(')','(');
}
public boolean isValid(String s) {
Stack<Character> st = new Stack<Character>();
for(int i = 0; i < s.length(); ++i){
//闭括号
char now = s.charAt(i);
if(mapping.containsKey(now)){
char topElement = st.empty() ? '#' : st.pop();
if(topElement != this.mapping.get(now)){
return false;
}
} else {
st.push(now);
}
}
return st.isEmpty();
}
}
执行结果:
时间复杂度:O(n),n为字符串长度。
几个知识点
定义一个栈
Stack<Integer> st = new Stack<Integer>();
//栈的两个方法
//弹出
st.pop();
//压入
st.push(xxx);
字符串的一个操作方法
String s = "abc";
s.charAt(0);//返回下标所对应的字符串