一、 问题描述
Leecode第二十题,题目为:
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: “()”
Output: true
Example 2:
Input: “()[]{}”
Output: true
Example 3:
Input: “(]”
Output: false
Example 4:
Input: “([)]”
Output: false
Example 5:
Input: “{[]}”
Output: true
问题理解为:
给定一个只包含字符’(’,’)’,’{’,’}’,’[‘和’]'的字符串,判断输入字符串是否有效。
输入字符串在下列情况下有效:
开括号必须由相同类型的括号对应。
开括号必须按正确的顺序对应。
注意,空字符串也被认为是有效的。
示例1:
输入:“()”
输出:正确
示例2:
输入:“()(){}”
输出:正确
示例3:
输入:“()”
输出:错误
示例4:
输入:“(())”
输出:错误
例5:
输入:“{[]}”
输出:正确
二、算法思路
1、
2、
三、实现代码
class Solution {
public boolean isValid(String s) {
Stack<Character> st = new Stack<Character>();
for(int i=0;i<s.length();i++){
if(s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[')
st.push(s.charAt(i));
else if(st.isEmpty() ||
s.charAt(i) == ')' && st.pop() != '(' ||
s.charAt(i) == '}' && st.pop() != '{' ||
s.charAt(i) == ']' && st.pop() != '[')
return false;
}
return st.size() == 0;
}
}