Algorithm
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
import java.util.Stack;
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '{' || c == '[' || c == '(') {
stack.push(c);
} else {
if (stack.isEmpty()) {
return false;
}
char topChar = stack.pop();
if (c == '}' && topChar != '{') {
return false;
}
if (c == ']' && topChar != '[') {
return false;
}
if (c == ')' && topChar != '(') {
return false;
}
}
}
return stack.isEmpty();
}
}
Review
Tip
关于选择
- 面对多个选择,展望一下各个选择的最终结果,在结果上进行斟酌。
- 明白自己的目标是什么,并确定优先级,然后进行选择
- 目标清晰才能井然有序
- 在发动汽车前一定要知道自己要往哪里去,还要知道选择什么途径去
- 在实现目标的方式上要灵活变通
Share
一般将先存放MSB所在字节的架构称为大端,将先存放LSB所在字节的架构称为小端。至于先放置MSB所在字节还是先放置LSB所在的字节,是由CPU的类型决定的。(近期设计的CPU有些可以在大端和小端之间切换)。
网友评论