系列文章:
LeetCode 热题 HOT 100(P1~P10)-优快云博客
LeetCode 热题 HOT 100(P11~P20)-优快云博客
LeetCode 热题 HOT 100(P21~P30)-优快云博客
LeetCode 热题 HOT 100(P31~P40)-优快云博客
LC020valid_parentheses
题目:
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串 s
,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
- 每个右括号都有一个对应的相同类型的左括号。
解法:
遇到右括号的时候需要判断有没有对应匹配的左括号,因为必须是类型相同的才能进行闭合,因此需要一个栈来维护遇到的左括号,看栈顶的左括号是否跟当前的右括号匹配。
static Map<Character, Character> cache = new HashMap<>();
static {
cache.put(')', '(');
cache.put('}', '{');
cache.put(']', '[');
}
public boolean isValid(String s) {
LinkedList<Character> stack = new LinkedList<>();
for (char c : s.toCharArray()) {
// 遇到右括号就需要一定要有匹配的左括号
if (cache.containsKey(c)) {
if (stack.isEmpty()) {
return false;
}
if (cache.get(c) != stack.pop()) {
return false;
}
} else {
//左括号的情况,直接入栈
stack.push(c);
}
}
return stack.isEmpty();
}
这里有个技巧,维护一个右括号为key 的map,这样方便判断和匹配。
LC021merge_two
题目:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
解法:
遇到链表题,直接创建一个pre 节点,接着轮流比较两边的大小,比较繁琐的是需要判断很多临界情况。
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode pre = new ListNode();
ListNode cur = pre;
while (list1 != null || list2 != null) {
ListNode next;
if (list1 == null) {
next = list2;
list2 = list2.next;
} else if (list2 == null) {
next = list1;
list1 = list1.next;
} else {
if (list1.val < list2.val) {
next = list1;
list1 = list1.next;
} else {
next = list2;