#include<stdAfx.h>
#include <iostream>
#include <stack>
#include <string>
using namespace std;
class Solution{
public:
string simplifyPath(string path){
int i=0;
int len=path.length();
stack<string> stk;
string str="";
string simpath="";
while(i<len){
if(path[i]=='/'){
if(str==".."){
if(!stk.empty())
stk.pop();
}
else{
if(str!="."&&str!="")
stk.push(str);
}
str="";
}
else{
str+=path[i];
}
i++;
}
cout<<str;
if(str==".."){
if(!stk.empty())
//cout<<"22222222";
stk.pop();
}
else if(str!="."&&str!=""){
stk.push(str);
}
if(stk.empty()){
return "/";
}
while(!stk.empty()){
simpath="/"+stk.top()+simpath;
stk.pop();
}
return simpath;
}
};
int main()
{
Solution s;
string str1="/..";
string res=s.simplifyPath(str1);
cout<<res;
cin>>str1;
}
使用栈,一个字符一个字符的判断,当遇到/时,入栈,没有遇到/时,累计字符形成字符串。for里面有两个大的判断分支。
leetcode simplify path
最新推荐文章于 2013-09-01 17:22:57 发布