LeetCode 简化路径(探索字节跳动)

题目描述

给定一个文档 (Unix-style) 的完全路径,请进行路径简化。

例如,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

边界情况:

  • 你是否考虑了 路径 = "/../" 的情况?
    在这种情况下,你需返回 "/" 。
  • 此外,路径中也可能包含多个斜杠 '/' ,如 "/home//foo/" 。
    在这种情况下,你可忽略多余的斜杠,返回 "/home/foo" 。

解题思路

对于每两个'/'之间的字符串,用一个数组来记录它们,分为以下几种情况:

  • 若是'.',直接跳过;
  • 若是"..",说明指代上一级目录,所以从数组中去掉最后加进去的子目录;
  • 若不为空,则将其加入数组中

最后依次用'/'按顺序将每个子目录组合成总路径。

代码

 1 class Solution {
 2 public:
 3     string simplifyPath(string path) {
 4         string res = "", temp = "";
 5         path += "/";
 6         vector<string> dirs;
 7         int len = path.length(), i = 0;
 8         while(i < len){
 9             if(path[i] == '/'){
10                 if(temp == ".."){
11                     if(dirs.size())
12                         dirs.pop_back();
13                 }
14                 else if(temp != "." && temp != "")
15                     dirs.push_back(temp);
16                 temp = "";
17                 while(i < len && path[i] == '/')
18                     i++;
19             }
20             else{
21                 temp += path[i++];
22             }
23         }
24         for(int i = 0; i < dirs.size(); i++){
25             res += "/";
26             res += dirs[i];
27         }
28         if(res == "") return "/";
29         return res;
30     }
31 };
原文地址:https://www.cnblogs.com/wmx24/p/10146066.html