标签:linked 遇到 void for rac 顺序 col 符号 span
题目描述:
给定一个只包括 ‘(‘,‘)‘,‘{‘,‘}‘,‘[‘,‘]‘ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
题目解析:
使用LinkedList作为辅助栈:
代码实现:
package com.company;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
String str = "]";
System.out.println(isValid(str));
}
private static boolean isValid(String s) {
if (s == null || s.isEmpty()) {
return true;
}
LinkedList<Character> linkedList = new LinkedList<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == ‘(‘ || ch == ‘[‘ || ch == ‘{‘) {
linkedList.add(ch);
} else {
//栈中没有元素,而当前符号为右括号,直接返回false,当前符号也不需要进栈
if (linkedList.isEmpty()) {
return false;
}
if (ch == ‘)‘) {
if (linkedList.peekLast() != ‘(‘) {
return false;
}
}
if (ch == ‘]‘) {
if (linkedList.peekLast() != ‘[‘) {
return false;
}
}
if (ch == ‘}‘) {
if (linkedList.peekLast() != ‘{‘){
return false;
}
}
if (!linkedList.isEmpty()) {
linkedList.removeLast();
}
}
}
return linkedList.isEmpty();
}
}
时间复杂度:O(N),遍历一遍,n为str的长度大小
空间复杂度:O(N),LinkedList的大小n,也就是辅助栈的大小
标签:linked 遇到 void for rac 顺序 col 符号 span
原文地址:https://www.cnblogs.com/ysw-go/p/11765463.html