the problem is here:
https://binarysearch.com/problems/Unix-Path-Resolution
Given a Unix
path, represented as a list of strings, return its resolved version.In Unix,
".."means to go to the previous directory and"."means to stay on the current directory. By resolving, we mean to evaluate the two symbols so that we get the final directory we're currently in.Constraints
n ≤ 100,000wherenis the length ofpathExample 1
Inputpath = ["usr", "..", "usr", ".", "local", "bin", "docker"]Output
["usr", "local", "bin", "docker"]Explanation
The input represents "/usr/../usr/./local/bin" which resolves to "/usr/local/bin/docker"Example 2
Inputpath = ["bin", "..", ".."]Output
[]Explanation
The input represents "/bin/../.." which resolves to "/"
my correct solution:
class Solution:
def solve(self, path):
stack = []
for s in path:
if s == "..":
if len(stack)> 0:
stack.pop()
elif s == ".": #if "elif" is replaced with "if" - it gives error
continue
else:
stack.append(s)
print(stack)
return stack
on this test case - ["..","..","..","..","..","..","."], the below code
class Solution:
def solve(self, path):
stack = []
for s in path:
if s == "..":
if len(stack)> 0:
stack.pop()
if s == ".": # "elif" is replaced with if and gives error
continue
else:
stack.append(s)
print(stack)
return stack
the expected result is [], but my code gives [".."] - wrong result.
The input is not a string where a for loop can mistake ".." vs "." - 1dot and 2dot.
The input is a list and it should clearly distinguish btw ".." and "." - so i assumed if/elif is not critical.
why does simple replacing elif with "if" gives wrong result?
sis not equal to"."you will append it to the stack, even if it's"..". You could add acontinuein theif s == "..":block to get the same behavior as with elif, but IMHOelifis the better choice and makes it clear that you have multiple cases to check and each one doing something different.return os.path.abspath('/'.join(path)).split("/")?