LeetCode Online Judge 题目C# 练习 - Simplify Path

Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/http://www.cnblogs.com/c/", => "/c"
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/".
In this case, you should ignore redundant slashes and return "/home/foo".

 1         public static string SimplifyPath(string s)
 2         {
 3             string[] arr = s.Split('/');
 4             Stack<string> stack = new Stack<string>();
 5 
 6             for (int i = 0; i < arr.Length; i++)
 7             {
 8                 if (arr[i] != "")
 9                 {
10                     if (arr[i] == "..")
11                     {
12                         if (stack.Count > 0)
13                             stack.Pop();
14                     }
15                     else if (arr[i] == ".")
16                     {
17                     }
18                     else
19                     {
20                         stack.Push(arr[i]);
21                     }
22                 }
23             }
24 
25             StringBuilder sb = new StringBuilder();
26 
27             while (stack.Count > 0)
28             {
29                 sb.Insert(0, "/" + stack.Pop());
30             }
31 
32             //solve corner case like "/../"
33             if (sb.Length == 0)
34                 sb.Append("/");
35 
36             return sb.ToString();
37         }

代码分析:

  把字符串先用Split('/') 分开。arr[i] == "" 表示多余的斜杠。arr[i] == ".."表示返回上一级,arr[i] == "." 可以忽略它。

  要记住最后如果结果为空,要加"/"回到根目录。

  为什么用StringBuilder 而不用 String? StringBuilder是mutable,string 是immutable。 如果多次反复修改字符串,StringBuilder效率高很多。下面这个link是有人测试后的结果,+25000次,string消耗时间706ms, StringBuilder 1ms。

http://blog.eliotpearson.com/c-string-versus-stringbuilder/

posted @ 2012-10-17 22:03  ETCOW  阅读(286)  评论(0编辑  收藏  举报