题目描述
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: “()”
输出: true
示例 2:
输入: “()[]{}”
输出: true
示例 3:
输入: “(]”
输出: false
示例 4:
输入: “([)]”
输出: false
示例 5:
输入: “{[]}”
输出: true
题解1
import java.util.Scanner;
import java.util.Stack;
public class leetcode20 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
boolean valid = isValid(str);
System.out.println(valid);
}
public static boolean isValid(String s) {
int length = s.length();
if (length%2==1){
return false;
}
Stack<String> left = new Stack<>();
char[] chars = s.toCharArray();
for (char aChar : chars) {
String single = String.valueOf(aChar);
if ("(".equals(single)||"{".equals(single)||"[".equals(single)){
left.push(single);
}else{
if (left.size()==0){
return false;
}
String rightsingle = left.pop();
if (")".equals(single)){
if (!"(".equals(rightsingle)){
return false;
}
}else if ("}".equals(single)){
if (!"{".equals(rightsingle)){
return false;
}
}else if ("]".equals(single)){
if (!"[".equals(rightsingle)){
return false;
}
;
}
}
}
if (left.size()!=0){
return false;
}
return true;
}
}
题解二
import java.util.*;
public class leetcode20version3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
boolean valid = isValid(str);
System.out.println(valid);
}
public static boolean isValid(String s){
int n = s.length();
if (n % 2 == 1) {
return false;
}
Map<Character, Character> pairs = new HashMap<Character, Character>() {{
put(')', '(');
put(']', '[');
put('}', '{');
}};
Deque<Character> stack = new LinkedList<Character>();
for (int i = 0; i < n; i++) {
char ch = s.charAt(i);
if (pairs.containsKey(ch)) {
if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
return false;
}
stack.pop();
} else {
stack.push(ch);
}
}
return stack.isEmpty();
}
}