对撞型 Palindrome

Trapping Rain Water

  • 经典题,有一种很巧妙的2 pointers解法实现O(N) Time and O(1) Space

  • how much can current position trap depends on the lower bar, min(leftmax, rightmax)

  • 2 pointers left and right

  • keep track of maxHeight from left and right, leftMax, rightMax

  • every iteration when move left or right pointer, always update leftMax and rightMax

  • then compare with leftMax and rightMax, the smaller one is the direction to move next

  • 有单调栈的思想

public int trap(int[] height) {
        int n = height.length;
        int left = 0, right = n - 1;
        int water = 0;
        int leftMax = 0, rightMax = 0;
        while (left < right) {
            leftMax = Math.max(leftMax, height[left]);
            rightMax = Math.max(rightMax, height[right]);
            if (leftMax < rightMax) {
                water += leftMax - height[left];
                left++;
            } else {
                water += rightMax - height[right];
                right--;
            }
        }
        return water;
    }

Longest Palindromic Substring

  • 这题可以用2 pointers实现O(N^2)的解法

  • iterate each index of String, always check 2 substring

  • isPalindrome(s, i - maxLen - 1, i) -> try len(maxLen + 2)

  • isPalindrome(s, i - maxLen, i) -> try len(maxLen + 1)

Reverse words in a String II

  • 给一个char array, 每个单词被empty space隔开

  • 要求 in place reverse words in a string

  • reverse the whole char array first

  • then reverse word one by one

Next Permutation

  • next permutation经典题,全文背诵,跟permutation关系不大

  • 4步走,默背

  • 51432, 从右往左找到第一个nums[i] < nums[i + 1] ->1

  • 再从右往左找到比nums[i]大的最小的数 nums[j] > nums[i], 找从右往左第一个比nums[i]大的数 ->2

  • swap nums[i] and nums[j] 52431

  • everse subset from i+1 th to the end->52134

Next Greater Element III

  • 给定一个int value N, 求比N大的最小的permutation, int value

  • 解法跟next permutation很像

Valid Palindrome II

  • 最多允许删除一个char

  • 也就是说当s.charAt(begin) != s.charAt(end)的时候

  • either delete s.charAt(begin) or delete s.charAt(end)

  • return isValid(s.substring(begin, end)) || isValid(s.substring(begin + 1, end + 1));

Last updated

Was this helpful?