leetcode 71. 简化路径
leetcode
class Solution {
public:
string simplifyPath(string path) {
std::vector<std::string> arrPathParts;
char lastChar = ' ';
int begin = -1;
int end = -1;
int i = 0;
while ( i < path.size() || begin >= 0 ) {
if ( i < path.size() ) {
if ( lastChar == '/' && path[i] != '/' ) {
begin = i;
end = -1;
} else if ( lastChar != '/' && path[i] == '/' ) {
end = i;
}
lastChar = path[i];
++i;
} else {
if ( end < 0 ) {
end = path.size();
}
}
if ( begin >= 0 && begin < end ) {
std::string strPart = path.substr( begin, end - begin );
if ( !strPart.empty() ) {
if ( strPart == ".." ) {
if ( !arrPathParts.empty() ) {
arrPathParts.pop_back();
}
} else if ( strPart != "." ) {
arrPathParts.push_back( strPart );
}
}
begin = -1;
end = -1;
}
}
std::string strSimplifyPath;
for ( int i = 0; i < arrPathParts.size(); ++i ) {
strSimplifyPath += "/" + arrPathParts[i];
}
if ( strSimplifyPath.empty() ) {
strSimplifyPath = "/";
}
return strSimplifyPath;
}
};
本文标题:leetcode 71. 简化路径
本文链接:https://www.haomeiwen.com/subject/myhemktx.html
网友评论