您的位置:首页 > 其它

LeetCode 71. Simplify Path

2016-04-04 18:01 344 查看
Unix-style的path中,"."表示当前目录下的子目录,".."表示返回上一级目录,"..."的话保留(Input:"/..." Expected answer:"/...")。

因此维护一个stack,存放路径中文件夹的名字name,将path打散(split)后,一段段读入,如果是"."则继续读入下一段,如果是".."则将name的顶端pop掉,注意此处要检测name是否为空,因为输入有"/../",如果这两种都不是就压入name栈中。

自己写了个split函数,把path按"/"分开,因为有检测tmp是否为空,所以nodes里的所有string均不为空。注意split中for循环后,如果tmp不为空要压入nodes中(path最后一部分可能为“/abcd")。

最后如果name栈为空,res设为"/",否则将栈内依次加入res。

注意!name.empty()的位置,不能写成if(nodes[i] == ".." && !name.empty()),否则".."会被压入name中。

class Solution {
public:
void split(string str, char ch, vector<string>& nodes){
string tmp = "";
for(int i = 0; i < str.length(); ++i){
if(str[i] == '/'){
if(tmp != ""){
nodes.push_back(tmp);
}
tmp = "";
}
else {
tmp += str[i];
}
}
if(tmp != "")//input: path = "/..." expected:"/..."
nodes.push_back(tmp);

}
string simplifyPath(string path) {
vector<string> nodes;
split(path, '/', nodes);
stack<string> name;
for(int i = 0; i < nodes.size(); ++i){
if(nodes[i] == ".") continue;//nodes[i] == "" ||
if(nodes[i] == ".."){//input: path = "/../"
if(!name.empty())
name.pop();
}
else
name.push(nodes[i]);
}
string res = "";
while(!name.empty()){
res = "/" + name.top() +  res;
name.pop();
}
if(res.empty()) res = "/";
return res;
}
};


另外一种split的写法,时间相同,注意这种写法nodes中的内容可能为空,因此读入nodes[i]时要检测是否为空,为空则继续(Input:"///" Expected answer:"/")。

class Solution {
public:

void split(string s, char delim, vector<string>& nodes) {
string temp;
stringstream ss;    //here
ss.str(s);                //here
while(getline(ss, temp, delim)) {
nodes.push_back(temp);
}
}
string simplifyPath(string path) {
vector<string> nodes;
split(path, '/', nodes);
stack<string> name;
for(int i = 0; i < nodes.size(); ++i){
if(nodes[i] == "" || nodes[i] == ".") continue;//
if(nodes[i] == ".."){//path = "/../"
if(!name.empty())
name.pop();
}
else
name.push(nodes[i]);
}
string res = "";
while(!name.empty()){
res = "/" + name.top() +  res;
name.pop();
}
if(res.empty()) res = "/";
return res;
}
};


总结一下,个人认为比较特殊的输入和标准输出:

Input Expected answer

"///" "/"

"/..." "/..."

"/../" "/"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: