[Leetcode] 71. Simplify Path 解题报告

来源:互联网 发布:阿里云服务器个人备案 编辑:程序博客网 时间:2024/06/06 18:10

题目

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".

思路

首先熟悉一下Unix-style的路径构成规则:

字符含义(英文)含义(中文)/root directory根目录/Directory Separator路径分隔符.Current Directory当前目录..Parent Directory上级目录~Home Directory家目录有了上述规则,就可以设计本题的思路:1)如果当前目录为“..”,则代表要返回上一层目录,所以将当前目录从结果中删除;2)如果当前目录是空或者".",代表该目录无意义,可以直接抛弃;3)如果是合法目录,则加入当前结果中。

实现技巧:1)可以在path的最后加入一个"/",这样可以统一提取两个“/”之间的字符串,简化程序逻辑;2)采用vector来模拟stack,因为vector除了具备stack的所有功能之外,还有从前到后顺序访问元素的优势,这样可以避免最后对stack中的元素进行反转的额外时间复杂度开销。

代码

class Solution {public:    string simplifyPath(string path) {        vector<string> st;      // we use vecctor to simulate stack         path += '/';            // for easier programming        for (int i = 1; i < path.size(); i++) {              int pos = path.find('/', i);              string tem = path.substr(i, pos - i);              if (tem == "..") {                  if(st.size() > 0) {                    st.pop_back();                  }            }              else if (tem.size() > 0 && tem != ".") {                st.push_back("/" + tem);              }            i = pos;          }          string ans;          for (auto val: st) {            ans += val;         }        return ans.size() == 0? "/" : ans;      }};


0 0
原创粉丝点击