您的位置:首页 > 其它

LeetCode 71. Simplify Path

2016-01-26 00:28 309 查看
https://leetcode.com/problems/simplify-path/

其实就是练习字符串处理吧 以前没有用过erase函数,总结下用法:

#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <iostream>

using namespace std;

int main() {
string str;
for(char i = 'a'; i<='z'; i++) {
str = str + i;
}
//string& erase ( size_t pos = 0, size_t n = npos );
//erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
str.erase(1, 2);
cout << "string& erase ( size_t pos = 0, size_t n = npos ) : " << str << endl;
//string& erase ( size_t pos = 0);从pos开始往后都不要了
cout << str.erase(20) << endl;

//iterator erase ( iterator position ); 删除position处的一个字符
string::iterator itr = str.begin();
str.erase(itr+3) ;
cout << str << endl;

//iterator erase ( iterator first, iterator last ); 删除从first到last之间的字符(first和last都是迭代器)
str.erase(itr+3, str.end());
cout << str << endl;

return 0;

}

然后上代码:
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <iostream>

using namespace std;

class Solution {
public:
void legal(string &str) {
int pos = str.find_first_of("/");
int lastpos = pos, np;
while( (np = str.substr(pos+1).find_first_of("/")) != str.npos ) {
pos = pos+1+np;
if(pos == lastpos+1) {
str.erase(pos,1); //这个函数 erase(pos)是pos之后的都erase
pos = lastpos;
} else {
lastpos = pos;
}
}
}

string simplifyPath(string str) {
if(str.size() >0 && str[str.size()-1] != '/') str = str + '/';
legal(str);
string ret;
int pos = 0 , lastpos = pos, np;
while( ( np=str.substr(pos+1).find_first_of("/") ) != -1 ) {
pos += np+1;

string tmp = str.substr(lastpos, pos-lastpos);
if(tmp == "/."){
lastpos = pos;
continue;
}
if(tmp == "/..") {
int last = ret.find_last_of("/");
ret = ret.substr(0, last);
lastpos = pos;
continue;
}
ret = ret + tmp;
lastpos = pos;
}
if(ret == "")return "/";
return ret;
}
};

int main() {
freopen("71.txt", "r", stdin);
string str;
while(cin >> str) {
Solution s;
cout << s.simplifyPath(str) << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: