private boolean validStr(String targetStr) {
if (targetStr == null || targetStr.isEmpty()) {
return true;
}
Character[] validChars = {'*', '(', ')'};
boolean isValid = targetStr.chars().allMatch(c -> Arrays.asList(validChars).stream().anyMatch(f -> f == c));
if (!isValid) {
return false;
}
Stack<Character> xAndLeftBracketStack = new Stack<>();
char x = '*';
char leftBracket = '(';
//char rightBracket = ')';
for (char c : targetStr.toCharArray()) {
if (c == x || c == leftBracket) {
xAndLeftBracketStack.push(c);
} else {
//右括号,优先消除左括号,如果没有左括号,消除最近入栈的*
int neeRmvIndex = xAndLeftBracketStack.lastIndexOf(leftBracket);
if (neeRmvIndex < 0) {
neeRmvIndex = xAndLeftBracketStack.lastIndexOf(x);
}
if (neeRmvIndex < 0) {
return false;
}
xAndLeftBracketStack.remove(neeRmvIndex);
}
}
//余下的只有*和左括号,处理之==》迭代xAndLeftBracketStack,'*'入栈xStack,遇到'(',将入栈的*出栈,以此成对消除。
Stack<Character> xStack = new Stack<>();
while(!xAndLeftBracketStack.isEmpty()) {
char c = xAndLeftBracketStack.pop();
if (c == x) {
xStack.push(c);
} else {
if (xStack.isEmpty()) {
return false;
}
xStack.pop();
}
}
return true;
}