给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
package com.zhr.stack;
import com.zhr.exception.CodeException;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* @ Author :zhenghaoran.
* @ Date :Created in 15:43 2019/1/21
* @ Description:
* 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
* <p>
* 有效字符串需满足:
* <p>
* 左括号必须用相同类型的右括号闭合。
* 左括号必须以正确的顺序闭合。
* 注意空字符串可被认为是有效字符串。
*/
public class ValidParentheses {
public static Map<Character,Character> map = new HashMap();
static{
map.put(')','(');
map.put(']','[');
map.put('}','{');
}
/**
* 只要有 '(',')' 小中大括号在一起的就 变成 "" 空串
*
* @param s
* @return
*/
public static boolean isValid(String s) {
int length;
do {
length = s.length();
s = s.replace("()", "").replace("[]", "").replace("{}", "");
} while (length != s.length());
return s.length() == 0;
}
/**
* 使用Stack的栈结构,如果是([{ 就放入堆当中,如果是)]}则看堆顶是否有之匹配,如果有则pop,最好要检查Stack是否为空
*
* @param s
* @return
*/
public static boolean isValidTwo(String s) throws CodeException {
char[] chs = s.toCharArray();
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < chs.length; i++) {
if (chs[i] == '{' || chs[i] == '[' || chs[i] == '(') {
stack.add(chs[i]);
}
if (chs[i] == '}' || chs[i] == ']' || chs[i] == ')') {
char match = chs[i] == '}' ? '{' : (chs[i] == ']' ? '[' : '(');
if (stack.isEmpty() || !stack.pop().equals(match)) {
return false;
}
}
}
return stack.isEmpty();
}
/**
* 优化 使用map
* @param s
* @return
* @throws CodeException
*/
public static boolean isValidThree(String s) throws CodeException {
char[] chs = s.toCharArray();
Stack<Character> stack = new Stack<Character>();
for(int i = 0;i < chs.length; i++){
if(!map.containsKey(chs[i])){
stack.push(chs[i]);
}else if(!stack.empty() && map.get(chs[i]) != stack.pop()) {
return false;
}
}
return stack.empty();
}
public static void main(String[] args) throws CodeException {
String str1 = "()[]{}";
String str2 = "()";
String str3 = "(]";
String str4 = "([)]";
String str5 = "{[]}";
String str6 = "((()())";
String str7 = ")(";
boolean valid1 = isValidThree(str1);
boolean valid2 = isValidThree(str2);
boolean valid3 = isValidThree(str3);
boolean valid4 = isValidThree(str4);
boolean valid5 = isValidThree(str5);
boolean valid6 = isValidThree(str6);
boolean valid7 = isValidThree(str7);
System.out.println(valid1);
System.out.println(valid2);
System.out.println(valid3);
System.out.println(valid4);
System.out.println(valid5);
System.out.println(valid6);
System.out.println(valid7);
}
}