码迷,mamicode.com
首页 > 其他好文 > 详细

Simplify Path

时间:2014-08-24 20:50:23      阅读:155      评论:0      收藏:0      [点我收藏+]

标签: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 };

 

Simplify Path

标签:style   blog   color   使用   io   for   div   log   amp   

原文地址:http://www.cnblogs.com/moderate-fish/p/3932831.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!