给定一个字符串,其中只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
例如:
"()" 有效
"()[]{}" 有效
"(]" 无效
"([)]" 无效
"{[]}" 有效
思路:考虑使用栈来操作
直接上代码
public boolean isValid(String s) {
// LinkedList可以很好的作为一个栈来使用
LinkedList<Integer> list = new LinkedList<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
list.add((int) c);
continue;
}
if (c == ')') {
if (list.size() == 0 || list.getLast() != '(') return false;
list.removeLast();
continue;
}
if (c == ']') {
if (list.size() == 0 || list.getLast() != '[') return false;
list.removeLast();
continue;
}
if (c == '}') {
if (list.size() == 0 || list.getLast() != '{') return false;
list.removeLast();
continue;
}
}
return list.isEmpty();
}
参考链接:https://blog.youkuaiyun.com/hixiaoxiaoniao/article/details/109727727