标签:style blog color 使用 io for div log amp
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 };
标签:style blog color 使用 io for div log amp
原文地址:http://www.cnblogs.com/moderate-fish/p/3932831.html