标签:一个 div 组成 target other substr cli bsp 注意
Given an absolute path for a file (Unix-style), simplify it.
For example,
path ="/home/", =>"/home"
path ="/a/./b/../../c/", =>"/c"
"/a/./b/../c/"
, => "/a/c"和path = "/a/./b/c/"
, => "/a/b/c"。规律如下:
1 class Solution { 2 public: 3 string simplifyPath(string path) 4 { 5 vector<string> res; 6 7 for(int i=0;i<path.size();) 8 { 9 i++; 10 if(i==path.size()) break; //注意i++后会越界 11 int flag=i; 12 while(path[i] !=‘/‘&&i<path.size()) //注意i++后会越界 13 i++; 14 15 string dir=path.substr(flag,i-flag); //substr()的参数为起点和个数 16 17 if( !dir.empty()&&dir !=".") 18 { 19 if(dir=="..") 20 { 21 if( !res.empty()) 22 res.pop_back(); 23 } 24 else 25 res.push_back(dir); 26 } 27 28 } 29 30 if(res.empty()) 31 return "/"; 32 33 string result; 34 for(int i=0;i<res.size();++i) 35 { 36 result+=‘/‘+res[i]; 37 } 38 39 return result; 40 } 41 };
还有一种同样的思路但是采用迭代器的,见连接1。
标签:一个 div 组成 target other substr cli bsp 注意
原文地址:http://www.cnblogs.com/love-yh/p/7082113.html