LeetCode--388. Longest Absolute File Path & 386. Lexicographical Numbers

Keywords: Java

388. Longest Absolute File Path
"dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" this string sequence is obtained by the depth first search (root traversal first) of the file directory tree, so you need to use the stack to parse this string to get all the full paths, so you can compare the length of the full path string. Note here that a subfolder may also contain subfolders and files, so with the help of monotone stack (the depth or level of each current relative path is monotonically increasing).

import javafx.util.Pair;
import java.util.LinkedList;
import java.util.Stack;

public class LongestAbsoluteFilePath {

    public static int lengthLongestPath(String input) {

        String[] lists = input.split("\n");
        LinkedList<Pair<String, Integer>> table = new LinkedList<>();
        for (String s : lists) {
            int count = 0;
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == '\t')
                    count++;
                else
                    break;
            }
            Pair<String, Integer> tmp = new Pair<>(s.substring(count), count);
            table.add(tmp);
        }

        Stack<Pair<String, Integer>> stack = new Stack<>();
        int ret = 0;
        int curr = 0;
        int wc = 0;
        for (Pair pair : table) {

            String key = (String) pair.getKey();
            Integer val = (Integer) pair.getValue();
            while (!stack.isEmpty() && stack.peek().getValue() >= val) {
                String s = stack.pop().getKey();
                curr -= s.length();
                wc -= 1;
            }
            stack.add(pair);
            curr += key.length();
            wc += 1;

            if (key.contains("."))
                ret = Math.max(ret, curr + wc - 1);
        }
        return ret;
    }

    public static void main(String[] args) {
        String ex="dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext";
        System.out.println(lengthLongestPath(ex));
        String[] tmp=ex.split("\n");
        for (String s:tmp)
            System.out.println(s);

    }
}

386. Lexicographical Numbers

class Solution {
    
    public static LinkedList<Integer> ret;
    public List<Integer> lexicalOrder(int n) {
        
        ret=new LinkedList<>();
        for(int i=1;i<=9;i++)
        {
            if(i<=n)
            {
                ret.add(i);
                dfs(i,n);
            }    
        }
        return ret;
    }
    
    public static void dfs(int num,int n){
        if(num>n)
            return;
        for(int i=0;i<=9;i++)
        {
            int t=num*10+i;
            if(t<=n){
                ret.add(t);
                dfs(t,n);
            }
            else
                break;
        }
    }   
}

Posted by jevman on Thu, 14 Nov 2019 07:28:56 -0800