给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
譬如:"()[]{}"为合法,"(]"、"([)]"均为非法。
思路:栈,遇到左括号入栈,非左括号出栈并检查是否匹配,如果不匹配则非法。如果整个字符串遍历完了且栈也为空,则合法。
代码:
public class ValidParentheses {
//定义栈
class Stack{
char[] ch;
int maxSize;
int head = -1;
public Stack(int maxSize) {
this.maxSize = maxSize;
ch = new char[maxSize];
}
public void push(char c) {
if(isFull()) {
ch = Arrays.copyOf(ch, 2*maxSize);
}
ch[++head] = c;
}
public char pop() {
if(isEmpty())
return ' ';
return ch[head--];
}
public boolean isEmpty() {
return head-1 < -1;
}
public boolean isFull() {
return head == maxSize-1;
}
}
public boolean isValid(String s) {
if(s.isEmpty())return true; //空串为真
Stack stack = new Stack(s.length());
for(int i = 0;i<s.length();i++) {
char t = s.charAt(i);
if(t == '('||t=='['||t=='{') { //左括号入栈
stack.push(t);
}else {
char t1 = stack.pop();
if(t1 == '('&&t == ')')continue;
else if (t1 == '['&&t == ']') continue;
else if (t1 == '{'&&t=='}') continue;
else {
return false;
}
}
}
if(stack.isEmpty())
return true;
else
return false;
}
public static void main(String[] args) {
System.out.println(new ValidParentheses().isValid("()[]{}"));
System.out.println(new ValidParentheses().isValid("(]"));
System.out.println(new ValidParentheses().isValid("([)]"));
System.out.println(new ValidParentheses().isValid("})]"));
}
}
运行结果: