71.Simplify Path
来源:互联网 发布:by2为什么不红了知乎 编辑:程序博客网 时间:2024/05/16 09:33
思路:用栈,遇到/./或者结尾是/.或者//什么都不做,继续遍历;遇到/../或者结尾是/..就将栈顶元素一直出栈直到遇到“/”为止;遇到其他元素就入栈。本题思路简单,但是写起来很容易出错。特别是在出栈前要判断栈是否为空,以及类似于/.../这样的情况怎么处理。
class Solution {
public:string simplifyPath(string path) {
//process
stack<char> result;
int len=path.size();
for(int i=0;i<len;++i){
if(path[i]=='/'){
if(i+2<len && path[i+1]=='.' && path[i+2]=='.' && (i+3>=len || path[i+3]=='/') ){
if(!result.empty()){
while(!result.empty() && result.top()!='/'){
result.pop();
}
result.pop();
}
i+=2;
}else if(i+1<len && path[i+1]=='.' && (i+2>=len || path[i+2]=='/')){
i+=1;
}else if(i+1<len && path[i+1]!='/'){
result.push(path[i]);//add '/'
}
}else{
result.push(path[i]);
}
}
//end
if(result.empty()){
return "/";
}
stack<char> reverse_result;
while(!result.empty()){
reverse_result.push(result.top());
result.pop();
}
string s;
while(!reverse_result.empty()){
s+=reverse_result.top();
reverse_result.pop();
}
return s;
}
};
0 0
- LeetCode 71. Simplify Path
- LeetCode --- 71. Simplify Path
- [Leetcode] 71. Simplify Path
- [leetcode] 71.Simplify Path
- 71.Simplify Path
- 71.Simplify Path
- 71. Simplify Path
- [leetcode] 71.Simplify Path
- 71. Simplify Path
- Leetcode 71. Simplify Path
- LeetCode 71. Simplify Path
- Leetcode 71. Simplify Path
- 71. Simplify Path LeetCode
- 71. Simplify Path
- 71. Simplify Path
- 71. Simplify Path
- 71. Simplify Path
- leetcode 71. Simplify Path
- Eclipse快捷键
- LAMP的环境的搭建
- java一些简单的知识
- 算法 线性排序-区间法
- 简单分析一下Android恢复出厂设置的流程
- 71.Simplify Path
- 三极管显身手 电平转换及驱动电路
- select函数
- About a full duplex ALSA application
- linux下,使用opencv训练级联分类器opencv_traincascade
- Xamarin iOS教程之显示和编辑文本
- 各种bar的隐藏
- Java基础--多线程
- UVA 11572 - Unique Snowflakes