首页 > 代码库 > 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