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

leetcode Simplify Path

时间:2014-11-13 00:26:19      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   sp   for   文件   

题目的意思是简化一个unix系统的路径。例如:

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

我尝试用逐个字符判断的方法,一直提交测试,发现要修改甚多的边界。于是就参考了这位大神

思路其实不会那么复杂,C#里面的话直接可以用split就可以分割string,c++中好像要委婉实现,例如 getline(ss,now,‘/‘)

在c++中getline(istream& is, string& str, char delim)

Extracts characters from is and stores them into str until the delimitation character delim is found

是指将is中的直到下一个delim字符间的数据给str,delim不会在str中,如果delim缺省,那么默认‘\n‘

因为文件流是往后读,读到文件末尾为止,所以用while来处理,详见代码。

(1)用“/”分割字符串,遍历每个分割部分,存入一个vector<string>中
(2)若当前分割部分为空,证明有连续的"/"或是最后一个“/”,忽略
(3)若当前部分为“.”,忽略
(4)若当前部分为“..”,若vector不为空,去除vector最后一个元素
(5)再将vector中的string用“/”连起来,得到结class Solution {public:
string simplifyPath(string path) {
        string ans,now;
        vector<string> list;
        stringstream ss(path);
        while(getline(ss,now,/))
        {
            if(now.length()==0 || now==".")
                continue;
            if(now=="..")
            {
                if(!list.empty())
                    list.pop_back();
            }
            else
            {
                list.push_back(now);
            }
        }
        for(int i=0; i<list.size(); i++)
        {
            ans += "/";
            ans += list[i];
        }
        if(ans.length()==0) ans = "/";
        return ans;
    }
};

 

leetcode Simplify Path

标签:style   blog   http   io   color   ar   sp   for   文件   

原文地址:http://www.cnblogs.com/higerzhang/p/4093843.html

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