Simplify Path--LeetCode

左手的ㄟ右手 2022-08-07 11:43 121阅读 0赞

题目:

Given an absolute path for a file (Unix-style), simplify it.

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. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <stack>
  5. using namespace std;
  6. /*
  7. 给一个Unix下面的路径表示方式
  8. 给出最终的结果 使用栈来消除复杂的表达方式
  9. */
  10. string SimplifyPath(string& str)
  11. {
  12. string result;
  13. stack<char> st;
  14. if(str.length() == 0 || str[0] !='/')
  15. return result;
  16. int i;
  17. char tmp;
  18. st.push(str[0]);
  19. for(i=1;i<str.length();i++)
  20. {
  21. tmp = st.top();
  22. if(isalpha(str[i])) //是字母
  23. st.push(str[i]);
  24. if(str[i]=='/' && i!=str.length()-1)
  25. {
  26. if(tmp != '/' && tmp != '.') // 斜线
  27. {
  28. st.push(str[i]);
  29. }
  30. if(tmp == '.')
  31. {
  32. st.pop();
  33. }
  34. }
  35. if(str[i]=='.') //逗点
  36. {
  37. if(tmp == '.')
  38. {
  39. st.pop();
  40. st.pop();
  41. if(!st.empty())
  42. tmp = st.top();
  43. while(!st.empty() && tmp != '/')
  44. {
  45. st.pop();
  46. tmp = st.top();
  47. }
  48. if(st.empty())
  49. st.push('/');
  50. }
  51. else
  52. st.push(str[i]);
  53. }
  54. }
  55. result.append(st.size(),'c');
  56. i=st.size()-1;
  57. while(!st.empty())
  58. {
  59. tmp = st.top();
  60. st.pop();
  61. result[i--] = tmp;
  62. }
  63. return result;
  64. }
  65. int main()
  66. {
  67. string str("/a/./b/../../c/");
  68. //string str("/../");
  69. cout<<SimplifyPath(str);
  70. return 0;
  71. }

发表评论

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

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

相关阅读