您的位置:首页 > 其它

LeetCode(71) Simplify Path

2015-07-27 11:01 537 查看
有解释的代码如下,参考水中的鱼

[code]class Solution {
public:
    string simplifyPath(string path) {

        int length = path.size();

        //处理长度为1的特例
        if(1 == length)

            return path;

        //预处理算法设计技术:将不符合要求的输入转换为符合要求的输入,
        //要求最后的一个字符一定为'/'以方便下面的处理,这种技巧很常用
        if(path[length - 1] != '/') {

            path = path + "/";
            length++;

        }

        stack<string> stackString;

        //每次提取出相邻'/'与'/'之间的字符串,如果为“//”,则提取出空字符串
        int index1, index2;
        index1 = 0;
        index2 = 1;
        while(index2 < length) {

            string tmpString;

            while(path[index2] != '/') {

                tmpString.push_back(path[index2]);
                index2++;

            }

            if(".." == tmpString) {

                if(stackString.size() != 0)

                   stackString.pop();

            }else {

                if(tmpString == "." || tmpString == "") {

                      //什么都不做

                }else {

                     stackString.push(tmpString);

                }

            }

            index1 = index2;
            index2++;

        }

        if(0 == stackString.size())

            return "/";

        string result;

        while(stackString.size() != 0) {

            result = "/" + stackString.top() + result;
            stackString.pop();

        }

        return result;

    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: