LeetCode -- Simplify Path
題目描述:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = /home/, => /home
path = /a/./b/../../c/, => /c
就是對一個UNIX風格的路徑簡化。
思路:
1. 將路徑用'/'分隔存在數組中,過濾掉值為.,/或空的元素
2. 遍歷數組的同時使用棧,如果值為..,如果棧有元素,彈出;如果值不為..入棧。
3. 最後對棧做一次遍歷拼簡化後的路徑就可以了。
實現代碼:
public class Solution {
public string SimplifyPath(string path) {
var folders = path.Split('/').Where(x=>x!=. && x != / && x != ).ToList();
var stack = new Stack();
for(var i = 0;i < folders.Count; i++){
if(folders[i] == ..){
if(stack.Count > 0){
stack.Pop();
}
}
else{
stack.Push(folders[i]);
}
}
var result = string.Empty;
while(stack.Count > 0){
var f = stack.Pop();
result = string.Format(/{0},f) + result;
}
if(result == string.Empty){
return /;
}
return result;
}
}