码迷,mamicode.com
首页 > 其他好文 > 详细

71. Simplify Path 解题记录

时间:2018-04-15 11:36:52      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:amp   ant   数组   +=   foo   absolute   empty   XA   ring   

题目描述:

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

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

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 class Solution {
 2 public:
 3     string simplifyPath(string path) {
 4         string ret, temp;
 5         int n = path.length();
 6         for (int i = 0; i < n; i++) {
 7             if (path[i] == /) {
 8                         //以‘/‘为触发添加情况
 9                 if (temp.empty())
10                                 //temp为空串
11                     continue;
12                 if (temp == ".") {
13                                 //temp为‘.‘
14                     temp.clear();
15                     continue;
16                 }
17                 if (temp == "..") {
18                                 //temp为".."
19                     int next = ret.rfind("/");
20                     if (next > 0)
21                                         //防止ret为空串,next为-1的情况
22                         ret.erase(ret.begin() + next, ret.end());
23                     else
24                         ret.clear();
25                     temp.clear();
26                 }
27                 else {
28                                 //添加
29                     ret = ret + / + temp;
30                     temp.clear();
31                 }
32             }
33             else
34                 temp += path[i];
35         }
36         if (temp == ".." && ret.length()>1) {
37                 //因为以‘/‘为添加条件,可能会碰到最后一个字符不是‘/‘的情况,所以最后要再比较一次
38             ret.erase(ret.begin() + ret.rfind("/"), ret.end());
39         }
40         if (temp != "." && temp != ".." && !temp.empty())
41             ret = ret + / + temp;
42         if (ret.empty())
43             ret = "/";
44         return ret;
45     }
46 };

 

71. Simplify Path 解题记录

标签:amp   ant   数组   +=   foo   absolute   empty   XA   ring   

原文地址:https://www.cnblogs.com/sakuya0000/p/8836228.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!