Day 35 of LeetCode

Day 35 of LeetCode

Β·

2 min read

Took a 2-day break. πŸ˜Άβ€πŸŒ«οΈ

Documenting LeetCode solving.

Q103

139. Word Break

Medium. 1D DP.

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        // e.g. "leetcode"
        int[] dp = new int[s.length() + 1];
        Arrays.fill(dp, -1);
        // base case, dp[8] ("") = true
        dp[s.length()] = 1;

        for (int i = s.length() - 1; i >= 0; i-- ) {
            for (String w : wordDict) {
                if ((i + w.length() <= s.length()) &&
                    w.equals(s.substring(i, i + w.length()))) {
                        dp[i] = dp[i + w.length()];
                }
                // found matching, break the loop
                if (dp[i] == 1) {
                    break;
                }
            }
        }

        return dp[0] == 1 ? true : false;
    }
}

Q104

300. Longest Increasing Subsequence

Medium. 1D DP.

class Solution {
    public int lengthOfLIS(int[] nums) {
        int[] dp = new int[nums.length];
        Arrays.fill(dp, 1);
        // reverse order
        for (int i = nums.length - 1; i >= 0; i--) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] < nums[j]) {
                    dp[i] = Math.max(dp[i], 1 + dp[j]);
                }
            }
        }

        int res = 0;
        for (int n : dp) {
            res = Math.max(res, n);
        }

        return res;
    }
}

R21

155. Min Stack

class MinStack {
    Stack<Integer> stack;
    Stack<Integer> minStack;

    public MinStack() {
        stack = new Stack<>();
        minStack = new Stack<>();
    }

    public void push(int val) {
        stack.push(val);
        // the peek item in minStack is always the smallest so far
        if (minStack.isEmpty() || val <= minStack.peek()) {
            minStack.push(val);
        }
    }

    public void pop() {
        if (stack.peek().equals(minStack.peek())) {
            minStack.pop();
        }
        stack.pop();
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return minStack.peek();
    }
}

Did you find this article valuable?

Support 🐰 Evelyn's Learning Journey by becoming a sponsor. Any amount is appreciated!

Β