Given a string A representing an absolute path for a file (Unix-style).
Return the string A after simplifying the absolute path.
Note:
Absolute path always begin with ’/’ ( root directory ).
Path will not have whitespace characters.
Input Format
The only argument given is string A.
Output Format
Return a string denoting the simplified absolute path for a file (Unix-style).
For Example
Input 1:
A = "/home/"
Output 1:
"/home"
Input 2:
A = "/a/./b/../../c/"
Output 2:
"/c"
Method:
Use a stack to keep track of the path, then pop the stack from bottom
Solution:
Time: O(n) Space: O(n)
public class Solution { public String simplifyPath(String A) { Deque<String> stack = new ArrayDeque<>(); String[] arr = A.split("/"); for (String c : arr) { if (c.equals("")) continue; if (c.equals(".")) continue; if (c.equals("..")) { if (!stack.isEmpty()) { stack.pop(); } } else { stack.push(c); } } StringBuilder sb = new StringBuilder(); while (!stack.isEmpty()) { sb.append("/"); sb.append(stack.pollLast()); } if (sb.length() == 0) sb.append("/"); return sb.toString(); } }