题解 | #有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return bool布尔型
*/
public boolean isValid (String s) {
boolean result = true;
// String s="([])";
Map<Character, Character> symbol = new HashMap<>();
symbol.put('(', ')');
symbol.put('[', ']');
symbol.put('{', '}');
Stack<Character> deq = new Stack<>();
Stack<Character> cache = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (symbol.values().contains(s.charAt(i))
|| symbol.keySet().contains(s.charAt(i))) {
deq.push(s.charAt(i));
}
}
if (deq.size() % 2 != 0) {
return false;
}
while (!deq.isEmpty()) {
Character lastSym = deq.pop();
if (symbol.values().contains(lastSym)) {
cache.push(lastSym);
continue;
}
if (symbol.keySet().contains(lastSym)) {
if(cache.isEmpty()){
result=false;
break;
}
Character endSym = cache.pop();
if (Objects.isNull(endSym) || !endSym.equals(symbol.get(lastSym))) {
result = false;
break;
}
}
}
return result;
}
}

