括号串合法性判断(栈实现)
作者:互联网
class Solution {
public boolean isValid(String s) {
boolean result = true;
char[] charsArray = s.toCharArray();
int stringLength = charsArray.length;
// 长度小于2或者长度不为偶数判定为假
if (stringLength < 2 || (stringLength & 1) == 1) {
result = false;
return result;
}
Stack<Character> characterStack = new Stack<>();
HashSet<Character> leftSet = new HashSet<>();
HashSet<Character> rightSet = new HashSet<>();
HashMap pairHashMap = new HashMap<Character, Character>();
leftSet.add('(');
leftSet.add('{');
leftSet.add('[');
rightSet.add(')');
rightSet.add('}');
rightSet.add(']');
pairHashMap.put(')', '(');
pairHashMap.put('}', '{');
pairHashMap.put(']', '[');
// 遍历字符串数组指针
int pointA = 0;
// 开始遍历字符串数组
while (pointA != stringLength) {
// 当前指针所指的字符串数组元素
char nowItem = charsArray[pointA];
// 对nowItem情况三种进行处理:1:开括号、闭括号、其他字符
if (leftSet.contains(nowItem)) {
characterStack.push(nowItem);
} else if (!characterStack.isEmpty() && rightSet.contains(nowItem)) {
Character topItem = characterStack.pop();
if (!(pairHashMap.get(nowItem) == topItem))
return false;
} else
return false;
pointA++;
}
// 如果栈中还剩下元素,则是有开括号未找到匹配
if (!characterStack.isEmpty())
result = false;
return result;
}
}
执行用时:2 ms, 在所有 Java 提交中击败了74.39% 的用户
内存消耗:36.6 MB, 在所有 Java 提交中击败了46.31% 的用户
标签:合法性,characterStack,nowItem,rightSet,括号,add,判断,result,leftSet 来源: https://blog.csdn.net/qq_40131916/article/details/119253141