General

Longest Absolute File Path

Suppose we abstract our file system by a string in the following manner:

The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents:

dir subdir1 subdir2 file.ext

  • Leetcode 388

  • '\t', '\n' 長度為1

  • Sting.split(), String.lastIndexOf()

  • sum[]紀錄目前長度

public int lengthLongestPath(String input) {
    if(input.equals("")) return 0;

    int[] sum = new int[input.length()+1];
    int ans = 0;

    for(String dir: input.split("\n")){
        int level = dir.lastIndexOf('\t') + 2;
        int len = dir.length() - level + 1;
        if(dir.contains(".")){
            ans = Math.max(ans, sum[level-1] + len);
        }else{
            sum[level] = sum[level-1] + len + 1;
        }
    }
    return ans;
}

Find Celebrity

  • Leetcode 277

390. Elimination Game

There is a list of sorted integers from 1 to n. Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.

Repeat the previous step again, but this time from right to left, remove the right most number and every other number from the remaining numbers.

Find the last number that remains starting with a list of length n.

Explain

621 Task Scheduler

Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle. You need to return the least number of intervals the CPU will take to finish all the given tasks.

  1. Heap

    • Take the most frequent character first as possible

    • Time O(n), Space O(1)

  1. Count extra slot

    • Time O(n), Space O(1)

    • sort O(26log26) is O(1)

Last updated

Was this helpful?