首页 > 代码库 > Simplify Path
Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
思路:本题使用栈来处理即可。此处我们使用list模拟栈操作。
1 class Solution { 2 public: 3 string simplifyPath( string path ) { 4 list<string> dirList; 5 size_t prev = 0, i = 0; 6 while( ++i < path.size() ) { 7 if( path[i] == ‘/‘ ) { 8 if( i-prev-1 > 0 ) { 9 string curDir = path.substr( prev+1, i-prev-1 );10 if( curDir == ".." ) {11 if( !dirList.empty() ) { dirList.pop_back(); }12 } else if( curDir != "." ) {13 dirList.push_back( curDir );14 }15 }16 prev = i;17 }18 }19 if( i-prev-1 > 0 ) {20 string curDir = path.substr( prev+1, i-prev-1 );21 if( curDir == ".." ) {22 if( !dirList.empty() ) { dirList.pop_back(); }23 } else if( curDir != "." ) {24 dirList.push_back( curDir );25 }26 }27 string result = "";28 for( auto iter = dirList.begin(); iter != dirList.end(); ++iter ) {29 result += "/" + *iter;30 }31 if( result.empty() ) { result = "/"; }32 return result;33 }34 };
Simplify Path
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。