Open youngyangyang04 opened 4 months ago
class Solution {
public boolean isValid(String s) {
if (s.length() % 2 != 0) return false;
Stack<Character> stack = new Stack<>(); // 1. not char
for (char c : s.toCharArray()) {
if (c == '(') stack.push(')');
else if (c == '{') stack.push('}');
else if (c == '[') stack.push(']');
else if (stack.isEmpty() || c != stack.pop()) return false;
}
return stack.isEmpty(); // 2. not !stack.isEmpty()
}
}
左括号匹配了就入栈右括号确实方便,但似乎没什么必要啊,逻辑上有点别扭,其实直接匹配也挺清晰易懂的
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function (s) {
let stack = []
for (let char of s) {
if (char == '(' || char == '[' || char == '{') {
stack.push(char)
} else if (char == ')') {
if (stack.pop() != '(') return false
} else if (char == ']') {
if (stack.pop() != '[') return false
} else if (char == '}') {
if (stack.pop() != '{') return false
}
}
return stack.length == 0
};
@MusherM
左括号匹配了就入栈右括号确实方便,但似乎没什么必要啊,逻辑上有点别扭,其实直接匹配也挺清晰易懂的
/** * @param {string} s * @return {boolean} */ var isValid = function (s) { let stack = [] for (let char of s) { if (char == '(' || char == '[' || char == '{') { stack.push(char) } else if (char == ')') { if (stack.pop() != '(') return false } else if (char == ']') { if (stack.pop() != '[') return false } else if (char == '}') { if (stack.pop() != '{') return false } } return stack.length == 0 };
是的 做一个映射map很容易判断
打卡
作者的优化代码,代码上简单一些,但是算法逻辑上没那么容易直观。
代码的可读性也很重要,作者这种写法,在时间、空间复杂度上没有替身,反而降低了代码的可读性,加大人的理解成本,属实没啥必要了
https://programmercarl.com/0020.%E6%9C%89%E6%95%88%E7%9A%84%E6%8B%AC%E5%8F%B7.html