forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
50 lines (48 loc) · 1.35 KB
/
Solution.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Solution {
public string SimplifyPath(string path) {
var stack = new Stack<string>();
var sb = new StringBuilder();
foreach (var ch in ((IEnumerable<char>)path).Concat(Enumerable.Repeat('/', 1)))
{
if (ch == '/')
{
if (sb.Length > 0)
{
var folder = sb.ToString();
sb.Clear();
switch (folder)
{
case ".":
break;
case "..":
if (stack.Any())
{
stack.Pop();
}
break;
default:
stack.Push(folder);
break;
}
}
}
else
{
sb.Append(ch);
}
}
if (stack.Count == 0)
{
sb.Append('/');
}
foreach (var folder in ((IEnumerable<string>)stack.ToList()).Reverse())
{
sb.Append('/');
sb.Append(folder);
}
return sb.ToString();
}
}