Advertisement
lifeiteng

388. Longest Absolute File Path

Sep 10th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.10 KB | None | 0 0
  1. class Solution {
  2.     public int lengthLongestPath(String input) {
  3.         String[] split = input.split("\\\n");
  4.         Stack<Integer> stack = new Stack<>();   // contains string length
  5.         int curLen = 0, maxLen = 0;
  6.         for(String str : split)
  7.         {
  8.             int lvl = getLev(str);
  9.             while(!stack.isEmpty() && stack.size() >= lvl) curLen -= stack.pop();
  10.             if(stack.isEmpty() || stack.size() < lvl)
  11.             {
  12.                 int len = getLen(str) + 1;  // + 1 for '/'
  13.                 stack.push(len);
  14.                 curLen += len;
  15.             }
  16.             if(str.indexOf('.') >= 0) maxLen = Math.max(maxLen, curLen - 1);
  17.         }
  18.         return maxLen;
  19.     }
  20.    
  21.     int getLen(String str)
  22.     {
  23.         int n = str.length();
  24.         for(int i = 0; i < n; i++) if(str.charAt(i) != '\t') return str.substring(i).length();
  25.         return n;
  26.     }
  27.    
  28.     int getLev(String str)
  29.     {
  30.         int lv = 1;
  31.         for(char ch : str.toCharArray())
  32.         {
  33.             if(ch != '\t') break;
  34.             lv++;
  35.         }
  36.         return lv;
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement