Simplify Path

题目:Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

思路:

顺序执行,首先循环一开始是找出第一个非/的字符,接下来保存到为/的字符串,

并判断是否为".",如果是,那就继续continue

如果是“..”,首先判断堆栈是否有数据,有数据,清除一个数据。

其他的就是存入这个字符串。在程序结尾处,就是先是添加“/”,再结尾附上字符串。

代码:

class Solution {
public:
    string simplifyPath(string path) {
        int len=path.length();
        int i=0;//代表具体位置
        
        vector<string> result;
        while(i<len){
            //去掉所有的////
            while( path[i]=='/') i++;       //  这个地方不加“ i< len”是没事的,因为开头就已经判断
            if(i==len)    break;
            
            //找出接下来的字符
            string temp;
            while(i<len && path[i]!='/'){   //  这个地方不加“ i< len”不行,因为上面i++可能会导致溢出
                temp.push_back(path[i++]);
            }
            if(temp==".")   continue;
            if(temp=="..") {
                if(!result.empty()){
                    result.pop_back();
                }
            }
            else {
                result.push_back(temp);
            }
        }
        
        //程序往下执行说明有数据
        string final;
        
        if(result.empty()){
            return "/";
        }
        for(int i=0;i<result.size();i++){
            final.append("/");
            final.append(result[i]);
        }
        return final;
    }
};


posted @ 2015-10-28 00:38  JSRGFJZ6  阅读(98)  评论(0编辑  收藏  举报