题目:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
Corner Cases:
- 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"
.
代码实现(未优化):
#include <iostream>
#include <stack>
#include <string>
using namespace std;
class Solution {
public:
string simplifyPath(string path) {
return SplitString(path,"/");
}
string SplitString(const string& s, const string& c)
{
stack<string>st;
int pos2 = s.find(c);
int pos1 = 0;
while(string::npos != pos2)
{
string te = s.substr(pos1, pos2-pos1);
if(te.length() > 0){
if(te.compare("..") == 0){
if(!st.empty())
st.pop();
}else if(te.compare(".") == 0){}
else{
st.push(te);
}
}
pos1 = pos2 + c.size();
pos2 = s.find(c, pos1);
}
if(pos1 != s.length()){
string te = s.substr(pos1);
if(te.compare("..") == 0){
if(!st.empty())
st.pop();
}else if(te.compare(".") == 0){}
else{
st.push(te);
}
}
string r = "";
while(st.empty() == NULL){
r = "/" + st.top() + r ;
st.pop();
}
if(r.compare("") == 0){
r = "/";
}
return r;
}
};
int main(){
Solution s = Solution();
string r = s.simplifyPath("///");
cout << r << endl;
}