Leetcode 71: Simplify Path

时间:2017-11-10 12:29:18   收藏:0   阅读:219

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

 

 1 public class Solution {
 2     public string SimplifyPath(string path) {
 3         if (path.Length == 0) return path;
 4         
 5         var pathes = path.Split(/);
 6         var list = new List<string>();
 7         var sb = new StringBuilder();
 8         
 9         foreach (var p in pathes)
10         {
11             if (p == "..")
12             {
13                 if (list.Count > 0)
14                 {
15                     list.RemoveAt(list.Count - 1);
16                 }
17             }
18             else if (p != "" && p != ".")
19             {
20                 list.Add(p);
21             }
22         }
23                 
24         sb.Append(/);
25         for (int i = 0; i < list.Count; i++)
26         {
27             sb.Append(list[i]);
28             
29             if (i != list.Count - 1)
30             {         
31                 sb.Append(/);       
32             }
33         }
34         
35         return sb.ToString();
36     }
37 }

 

原文:http://www.cnblogs.com/liangmou/p/7813782.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!