|
1 | 1 | package newProblems;
|
2 | 2 |
|
| 3 | +import java.util.Stack; |
| 4 | + |
3 | 5 | /*
|
4 | 6 | Suppose we abstract our file system by a string in the following manner:
|
5 | 7 |
|
@@ -36,8 +38,41 @@ We are interested in finding the longest (number of characters) absolute path to
|
36 | 38 |
|
37 | 39 | public class LongestAbsoluteFilePath
|
38 | 40 | {
|
39 |
| - public int lengthLongestPath( String input ) |
40 |
| - { |
41 |
| - return 0; |
42 |
| - } |
| 41 | + public int lengthLongestPath( String input ) |
| 42 | + { |
| 43 | + String[] tokens = input.split( "\n" ); |
| 44 | + int result = 0; |
| 45 | + int currPathLength = 0; |
| 46 | + Stack<Integer> stack = new Stack<>(); |
| 47 | + |
| 48 | + for ( String token : tokens ) |
| 49 | + { |
| 50 | + int level = countLevel( token ); |
| 51 | + |
| 52 | + // if current directory/file depth is lower that the top |
| 53 | + // directory/file on the stack, pop from stack |
| 54 | + while ( stack.size() > level ) |
| 55 | + { |
| 56 | + currPathLength -= stack.pop(); |
| 57 | + } |
| 58 | + |
| 59 | + // +1 here because a "/" needs to be counted following each diretory |
| 60 | + int tokenLength = token.replaceAll( "\t", "" ).length() + 1; |
| 61 | + currPathLength += tokenLength; |
| 62 | + |
| 63 | + // if s contains ".", we have found a file! |
| 64 | + if ( token.contains( "." ) ) |
| 65 | + { |
| 66 | + result = currPathLength - 1 > result ? currPathLength - 1 : result; |
| 67 | + } |
| 68 | + stack.add( tokenLength ); |
| 69 | + } |
| 70 | + return result; |
| 71 | + } |
| 72 | + |
| 73 | + private int countLevel( String s ) |
| 74 | + { |
| 75 | + String cur = s.replaceAll( "\t", "" ); |
| 76 | + return s.length() - cur.length(); |
| 77 | + } |
43 | 78 | }
|
0 commit comments