leetcode 71. Simplify Path C++的stringstream分割字符串的一个很好地例子
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
click to show corner cases.
Corner Cases:
Did you consider the case where path = “/../”?
In this case, you should return “/”.
Another corner case is the path might contain multiple slashes ‘/’ together, such as “/home//foo/”.
In this case, you should ignore redundant slashes and return “/home/foo”.
题意很简单,就是化简文件路劲,这道题可以通过压栈来做,主要思路如下:
1)遇到文件夹直接入栈;
2)遇到“..”出栈;
3)遇到“.”不做任何处理,continue。
这道题的难点就是处理各种的exception。
代码如下:
import java.util.Stack;
/*
* 这道题很简单就是一个简单的使用栈解决的问题
* 这道题的难点主要在于处理各种的异常
*
* 你比如 /...这里直接就把...处理为一个元素
* */
public class Solution
{
public String simplifyPath(String path)
{
if(path==null || path.length()<=0)
return "/";
//比如字符串 /.按照'/'分割之后就是两个元素,一个是"",另一个是"."
String[] array=path.split("/");
if(array.length==0) //处理 "/"
return "/";
Stack<String> stack=new Stack<>();
for(int i=0;i<array.length;i++)
{
if(array[i].equals("") || array[i].equals("."))
continue;
else if(array[i].equals(".."))
{
if(stack.isEmpty()==false)
stack.pop();
}else
stack.add(array[i]);
}
if(stack.isEmpty())
return "/";
else
{
String res="";
while(stack.isEmpty()==false)
res="/"+stack.pop()+res;
return res;
}
}
}
下面是C++的做法,这个道题难点是字符串的分割,这个要用到stringstream,要记住这么使用
代码如下:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <stack>
using namespace std;
class Solution
{
public:
string simplifyPath(string path)
{
string res, tmp;
vector<string> stk;
stringstream ss(path);
while (getline(ss, tmp, '/'))
{
if (tmp == "" || tmp == ".")
continue;
if (tmp == ".." && !stk.empty())
stk.pop_back();
else if (tmp != "..")
stk.push_back(tmp);
}
for (auto str : stk)
res += "/" + str;
return res.empty() ? "/" : res;
}
};
还没有评论,来说两句吧...