Given an absolute path for a file (Unix-style), simplify it.
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
简化IP地址。
思路:利用string.Split来吧字符串分成字符串组,然后通过堆栈来存放有效名称。遇到/../则后退一格, /./则无视,//也无视。最后别忘了/../这种特殊情况。要返回/。
public class Solution {
public string SimplifyPath(string path) {
string[] arr = path.Split('/');
Stack<string> stack = new Stack<string>();
for (int i = 0; i < arr.Length; i++){
if (arr[i] != ""){
if (arr[i] == ".."){
if (stack.Count > 0)
stack.Pop();
}
else if (arr[i] == ".")
{
}
else
{
stack.Push(arr[i]);
}
}
}
StringBuilder sb = new StringBuilder();
while (stack.Count > 0){
sb.Insert(0, "/" + stack.Pop());
}
//solve corner case like "/../"
if (sb.Length == 0)
sb.Append("/");
return sb.ToString();
}
}