Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
Path="/home/", ="/home"
Path="/a/./b/../../c/", ="/c"
Click to show corner cases.
Corner Cases:
- Did you consider the case where path =
"/../" ?
In this case, you should return "/" .
- Another corner case is the path might contain multiple slashes
‘/‘ together, such as "/home//foo/" .
Should ignore redundant slashes and return "/home/foo" .
Problem Solving Ideas:
The path of simplification. Can be recorded with a stack. Traverse the original path and encounter/To determine the most recent word. If the "." Then do nothing. If "...", pop up the top element of the stack, otherwise into the stack.
One of the more ingenious ways is to add a slash directly behind the path, so you can avoid a slash or a slash behind the discussion.
Class Solution {public: string Simplifypath (string path) { stack<string> ss; Path = path + "/"; int len = Path.length (); String s= ""; for (int i=0; i<len; i++) { if (path[i]== '/') { if (s== ":") { if (!ss.empty ()) { ss.pop (); } } else if (s!= "" &&s!= ".") { Ss.push (s); } S= ""; } else{ s=s+path[i]; } } while (!ss.empty ()) { s = string ("/") + ss.top () + S; Ss.pop (); } if (s== "") { s= "/"; } return s; };
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] Simplify Path