Skip to content

Commit 5d56c84

Browse files
author
freemanzhang
committed
init impl
1 parent 36aaeb1 commit 5d56c84

File tree

1 file changed

+39
-4
lines changed

1 file changed

+39
-4
lines changed

src/newProblems/LongestAbsoluteFilePath.java

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package newProblems;
22

3+
import java.util.Stack;
4+
35
/*
46
Suppose we abstract our file system by a string in the following manner:
57
@@ -36,8 +38,41 @@ We are interested in finding the longest (number of characters) absolute path to
3638

3739
public class LongestAbsoluteFilePath
3840
{
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+
}
4378
}

0 commit comments

Comments
 (0)