LeetCode -- Simplify Path
Description:
Given an absolute path for a file (Unix-style), simplify it.
For example,
Path =/home/, =>/home
Path =/a/./B/.../../c/, =>/c
Is to simplify a UNIX-style path.
Ideas:
1. Separate the path with '/' in the array and filter out elements with a value of.,/or null.
2. Use the stack when traversing the array. If the value is..., if the stack has elements, it will pop up. If the value is not.
3. Finally, we can traverse and spell the simplified path of the stack.
Implementation Code:
public class Solution { public string SimplifyPath(string path) { var folders = path.Split('/').Where(x=>x!=. && x != / && x != ).ToList(); var stack = new Stack
(); for(var i = 0;i < folders.Count; i++){ if(folders[i] == ..){ if(stack.Count > 0){ stack.Pop(); } } else{ stack.Push(folders[i]); } } var result = string.Empty; while(stack.Count > 0){ var f = stack.Pop(); result = string.Format(/{0},f) + result; } if(result == string.Empty){ return /; } return result; }}