[力扣] 算法 19~21 (C#)

19. 删除链表的倒数第 N 个结点

public class Solution {
    public ListNode RemoveNthFromEnd(ListNode head, int n) {
        var pre = new ListNode(0, head);
        var fast = pre;
        while (n-- > 0)
            fast = fast.next;
        var slow = pre;
        while (fast.next != null)
            (fast, slow) = (fast.next, slow.next);
        slow.next = slow.next.next;
        return pre.next;
    }
}

20. 有效的括号

public class Solution {
    public bool IsValid(string s) {
        var pair = new Dictionary<char, char>() { [')'] = '(', ['}'] = '{', [']'] = '[', };
        var stack = new Stack<char>();
        for (var i = 0; i < s.Length; i++)
        {
            var ch = s[i];
            if (stack.Count > s.Length - i)
                return false;
            if (pair.TryGetValue(ch, out var partner))
            {
                if (!stack.TryPop(out var top) || top != partner)
                    return false;
            }
            else
            {
                stack.Push(ch);
            }
        }
        return stack.Count == 0;
    }
}

21. 合并两个有序链表

public class Solution {
    public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
        var head = new ListNode();
        var curr = head;
        while (l1 != null && l2 != null)
        {
            ref var rmv = ref (l1.val < l2.val ? ref l1 : ref l2);
            curr.next = rmv;
            rmv = rmv.next;
            curr = curr.next;
        }
        curr.next = l1 ?? l2;
        return head.next;
    }
}

发表评论