• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
71. Simplify Path

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".
class Solution {
public:
    string simplifyPath(string path) {
        int l = path.size(), i, j;
        i = 0;
        string s;
        vector<string> v;
        while(i >= 0 && i < l)
        {
            while(path[i] == '/')
                i++;
            if(i >= l)
                break;
            j = path.find("/", i);
            if(-1 == j)
                s = path.substr(i);
            else
                s = path.substr(i, j-i);
            if(s == "..")
            {
                if(v.size())
                    v.erase(v.end()-1);
            }
            else if(s != ".")
                v.insert(v.end(), s);
            i = j;
        }
        if(!v.size())
            return "/";
        s = "";
        for(i=0; i<v.size(); i++)
        {
            s += "/";
            s += v[i];
        }
        return s;
    }
};

 

测试用例:

"/." -- "/"

"/../" -- "/"

"/home/" -- "/home"

"/a/./b/../../c/" -- "/c"

posted on 2016-03-13 23:24  ArgenBarbie  阅读(146)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3