ITPub博客

首页 > > > [LeetCode] Simplify Path

[LeetCode] Simplify Path

作者:Ruiyuan Li 时间:2015-07-28 00:00:00 0 删除 编辑

Simplify Path

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

解题思路:

化简路径。可以用一个栈来记录。遍历原路径,遇到/,则判断最近一个单词。若为"."则什么也不做。若"..",弹出栈顶元素,否则入栈。

有一个比较巧的办法是,直接在path后面添加一个斜杠,这样就能避免讨论后面有斜杠还是没有斜杠了。

class Solution {
public:
    string simplifyPath(string path) {
        stack ss;
        path = path + "/";
        int len = path.length();
        string s="";
        for(int i=0; i


转载请注明: » [LeetCode] Simplify Path
<!-- -->

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4825