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[]紀錄目前長度
publicintlengthLongestPath(String input) {if(input.equals("")) return0;int[] sum =newint[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
publicintfindCelebrity(int n) {int cele =0; // select candidatefor(int i=1; i<n; i++){if(knows(cele, i)){ cele = i; } }// test if candidate knows othersfor(int i=0; i<cele; i++){if(knows(cele, i)) return-1; }// test if everyone knowsfor(int i=0; i<n; i++){if(i != cele &&!knows(i, cele)) return-1; }return cele;}
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.
deflastRemaining(self,n:int) ->int: head =1 step =1 goLeft =Truewhile n >1:if goLeft or n %2==1: head += step step *=2 n //=2 goLeft =not goLeftreturn head
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.
Heap
Take the most frequent character first as possible