LeetCode刷题日记(Day6)

Problem 19. Remove Nth Node From End of List

  • 题目描述
    Given a linked list, remove the n-th node from the end of list and return its head.

  • 解题思路
    要删除链表中倒数第 n 个节点,可以采取双指针的办法,一个快指针 cur,一个慢指针 pre,其中快指针 cur 始终领先慢指针 pre n个节点。则当快指针 cur 到达链表尾部时,慢指针pre恰好出现在要删除的元素的前边。只需要执行 pre -> next = pre ->next->next 操作即可将要删除的元素从链表中抹去。

  • 代码实现

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if (head -> next == NULL) 
            return NULL;
        ListNode *pre = head, *cur = head;
        for(int i = 0; i < n; i++) 
            cur = cur -> next;
        if (cur == NULL) 
            return head -> next;
        while(cur -> next){
            cur = cur->next;
            pre = pre->next;
        }
        pre -> next = pre ->next->next;
        return head;
    }
};

Problem 20. Valid Parentheses

  • 题目描述
    Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
    An input string is valid if:

    1. Open brackets must be closed by the same type of brackets.
    2. Open brackets must be closed in the correct order.
  • 解题思路
    因为每一个左括号都必须要跟一个右括号匹配,所以这里采用了 stack 数据结构。对输入的字符串进行遍历:

  1. 如果 s[i] 为左括号,则压入栈中;如果 s[i] 为右括号,则将栈顶元素取出,判断能否与 s[i] 匹配,不能则返回 false(如果栈为空,同样返回false)。
  2. 遍历完后,判断栈是否为空,若空则返回 true,否则返回 false。
  • 代码实现
class Solution {
public:
    bool isValid(string s) {
        stack<char> myStack;
        for(int i = 0; i < s.length(); ++i){
            switch(s[i]){
                case ')':
                    if (myStack.empty() || myStack.top() != '('){
                        return false;
                    }
                    myStack.pop();  
                    break;
                case ']':
                    if (myStack.empty() || myStack.top() != '['){
                        return false;
                    }
                    myStack.pop();
                    break;
                case '}':
                    if (myStack.empty() || myStack.top() != '{'){
                        return false;
                    }
                    myStack.pop();
                    break;
                default :
                    myStack.push(s[i]);
                    break;
            }
        }
        return myStack.empty();
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_36348299/article/details/88425461