leetcode 71. Simplify Path C++的stringstream分割字符串的一个很好地例子

蔚落 2022-06-08 01:23 299阅读 0赞

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。

代码如下:

  1. import java.util.Stack;
  2. /*
  3. * 这道题很简单就是一个简单的使用栈解决的问题
  4. * 这道题的难点主要在于处理各种的异常
  5. *
  6. * 你比如 /...这里直接就把...处理为一个元素
  7. * */
  8. public class Solution
  9. {
  10. public String simplifyPath(String path)
  11. {
  12. if(path==null || path.length()<=0)
  13. return "/";
  14. //比如字符串 /.按照'/'分割之后就是两个元素,一个是"",另一个是"."
  15. String[] array=path.split("/");
  16. if(array.length==0) //处理 "/"
  17. return "/";
  18. Stack<String> stack=new Stack<>();
  19. for(int i=0;i<array.length;i++)
  20. {
  21. if(array[i].equals("") || array[i].equals("."))
  22. continue;
  23. else if(array[i].equals(".."))
  24. {
  25. if(stack.isEmpty()==false)
  26. stack.pop();
  27. }else
  28. stack.add(array[i]);
  29. }
  30. if(stack.isEmpty())
  31. return "/";
  32. else
  33. {
  34. String res="";
  35. while(stack.isEmpty()==false)
  36. res="/"+stack.pop()+res;
  37. return res;
  38. }
  39. }
  40. }

下面是C++的做法,这个道题难点是字符串的分割,这个要用到stringstream,要记住这么使用

代码如下:

  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. #include <vector>
  5. #include <stack>
  6. using namespace std;
  7. class Solution
  8. {
  9. public:
  10. string simplifyPath(string path)
  11. {
  12. string res, tmp;
  13. vector<string> stk;
  14. stringstream ss(path);
  15. while (getline(ss, tmp, '/'))
  16. {
  17. if (tmp == "" || tmp == ".")
  18. continue;
  19. if (tmp == ".." && !stk.empty())
  20. stk.pop_back();
  21. else if (tmp != "..")
  22. stk.push_back(tmp);
  23. }
  24. for (auto str : stk)
  25. res += "/" + str;
  26. return res.empty() ? "/" : res;
  27. }
  28. };

发表评论

表情:
评论列表 (有 0 条评论,299人围观)

还没有评论,来说两句吧...

相关阅读