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

LeetCode Simplify Path

时间:2014-06-04 20:15:49      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

bubuko.com,布布扣
class Solution {
public:
    string simplifyPath(string path) {
        int len = path.length();
        if (len < 2) return "/";

        vector<string> spath;

        int p = -1, q = 0;

        // seperate the path into parts & simplify it with a stack
        while (q < len) {
            while (q < len && path[q] != /) q++;
            if (p + 1 < q) {
                add_part_to_spath(path.substr(p + 1, q - p - 1), spath);
            }
            p = q;
            q++;
        }

        // build the final simplified path
        string res;
        for (int i=0; i<spath.size(); i++) {
            res.push_back(/);
            res.append(spath[i]);
        }
        if (res.length() == 0) res = "/";
        return res;

    }

    void add_part_to_spath(string part, vector<string>& spath) {
        if (part == ".") {
            // do nothing;
        } else if (part == "..") {
            // goto the parent path part
            if (!spath.empty()) spath.pop_back();
        } else {
            // enter a new part
            spath.push_back(part);
        }

    }
};
bubuko.com,布布扣

 也可以直接在原有字符串上操作,但还是这样简单明了一些

LeetCode Simplify Path,布布扣,bubuko.com

LeetCode Simplify Path

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/lailailai/p/3759523.html

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