题解 | #合法的括号字符串#
合法的括号字符串
https://www.nowcoder.com/practice/eceb50e041ec40bd93240b8b3b62d221
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return bool布尔型
*/
public boolean isValidString (String s) {
// write code here
int count = 0;
int start = 0;
MyStack stack = new MyStack(s.length());
for (int i = 0; i < s.length(); i++) {
char current = s.charAt(i);
switch (current) {
case '(':
stack.pop(current,count);
break;
case ')':
if (!stack.isEmpty()) {
stack.push();
stack.pushStart();
} else {
count--;
if (count <0)
return false;
}
break;
case '*':
count++;
break;
default:
break;
}
if (i == s.length() - 1 && !stack.isEmpty()) {
int rightStart = count - stack.getStar();
if(rightStart<stack.getSize())
return false;
}
}
return true;
}
class MyStack {
int maxSize;
char[] chars;
int pos = -1;
int spos = -1;
int leftStars[];
MyStack(int max) {
maxSize = max;
chars = new char[maxSize];
leftStars = new int[maxSize];
}
public void pop(char ch,int star) {
chars[++pos] = ch;
leftStars[++spos] = star;
}
public char push() {
return chars[pos--];
}
public int pushStart(){
return leftStars[spos--];
}
public int getStar(){
return leftStars[spos];
}
boolean isEmpty() {
return pos == -1;
}
public char peek() {
return chars[pos];
}
public int getPos() {
return pos;
}
public int getSize(){
return pos+1;
}
}
}