[LeetCode] 101: Simplify Path
来源:互联网 发布:布拉格之春 知乎 编辑:程序博客网 时间:2024/06/05 00:08
[Problem]
[Solution]
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
- 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"
.
[Solution]
class Solution {说明:版权所有,转载请注明出处。Coder007的博客
public:
string simplifyPath(string path) {
// Note: The Solution object is instantiated only once and is reused by each test case.
stack<string> myStack;
int i = 0, j = 0;
// move i to the position of the first path
while(i < path.size() && path[i] == '/')i++;
// add all path into the stack
while(i < path.size()){
j = i;
while(j < path.size() && path[j] != '/'){
j++;
}
// sub path
string sub = path.substr(i, j-i);
if(sub == ".."){
if(!myStack.empty()){
myStack.pop();
}
}
else if(sub.size() > 0 && sub != "."){
myStack.push(sub);
}
i = j+1;
}
// generate result
string res = "";
while(!myStack.empty()){
res = "/" + myStack.top() + res;
myStack.pop();
}
if(res == "")res = "/";
return res;
}
};
阅读全文
0 0
- [LeetCode] 101: Simplify Path
- LeetCode: Simplify Path
- LeetCode Simplify Path
- LeetCode : Simplify Path
- [Leetcode] Simplify Path
- [leetcode] simplify path
- [LeetCode] Simplify Path
- leetcode 100: Simplify Path
- [leetcode]Simplify Path
- [LeetCode]Simplify Path
- [leetCode] Simplify Path
- [leetcode]Simplify Path
- [leetcode] Simplify Path
- [LeetCode] Simplify Path
- leetcode simplify path
- Leetcode: Simplify Path
- LeetCode题解:Simplify Path
- [LeetCode] Simplify Path
- [LeetCode] 098: Search in Rotated Sorted Array II
- any and all
- [LeetCode] 099: Search Insert Position
- 深度学习论文(十)---Multiple-Human Parsing in the Wild
- [LeetCode] 100: Set Matrix Zeroes
- [LeetCode] 101: Simplify Path
- [LeetCode] 102: Single Number
- [LeetCode] 103: Single Number II
- photoshop下载教程
- [LeetCode] 104: Sort Colors
- [LeetCode] 105: Spiral Matrix
- [LeetCode] 106: Spiral Matrix II
- [LeetCode] 107: Sqrt(x)
- [LeetCode] 108: String to Integer