标签:course 遍历 hat desc str table this from split
Given an absolute path for a file (Unix-style), simplify it.
For example,
path ="/home/", =>"/home"
path ="/a/./b/../../c/", =>"/c"
(1) |
istream& getline (istream& is, string& str, char delim); istream& getline (istream&& is, string& str, char delim); |
---|---|
(2) |
istream& getline (istream& is, string& str); istream& getline (istream&& is, string& str); |
题解:
自己的版本,由于不知道c++对应Java split()的函数
1 /* 2 思路: 3 "/" "/" 4 "/../" "/" 5 "/home//foo/" "/home/foo" 6 "/home/./foo/" "/home/foo" 7 "/home/a/../foo/" "/home/foo" 8 "/home/foo" "/home/foo" 9 */ 10 #include<string> 11 #include<vector> 12 #include<sstream> 13 using namespace std; 14 class Solution { 15 public: 16 string simplifyPath(string path) { 17 vector<string> str; 18 ostringstream oss; 19 for(int i = 0; i < path.length();i++){ 20 if(path[i] == ‘/‘ || i == path.length() - 1){ 21 if(path[i] != ‘/‘ && i == path.length() - 1) oss<<path[i]; 22 string temp = oss.str(); 23 if(temp == "" || temp == "."){} 24 else if(temp == ".."){ 25 if(str.size() != 0){ 26 str.pop_back(); 27 } 28 }else{ 29 str.push_back(temp); 30 } 31 oss.str(""); 32 }else{ 33 oss<<path[i]; 34 } 35 } 36 oss.str(""); 37 for(int i=0;i<str.size();i++){ 38 oss<<"/"<<str[i]; 39 } 40 if(str.size() == 0){ 41 return "/"; 42 } 43 return oss.str(); 44 } 45 };
参考版本:
1 class Solution { 2 public: 3 string simplifyPath(string path) 4 { 5 vector<string> res; 6 stringstream ss(path); 7 string sub; 8 while(getline(ss,sub,‘/‘)) 9 { 10 if(sub=="." || sub=="") 11 continue; 12 else if(sub==".." && res.size()) 13 res.pop_back(); 14 else if(sub != "..") 15 res.push_back(sub); 16 } 17 string result; 18 for(string temp : res) 19 result += ‘/‘+temp; 20 return res.empty() ? "/" : result; 21 } 22 };
标签:course 遍历 hat desc str table this from split
原文地址:https://www.cnblogs.com/yfzhou/p/9684080.html