Simplify Path

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

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

click to show corner cases.

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".

参考:http://blog.csdn.net/maverick1990/article/details/23275051

题意:简化一个Unix文件路径,注意:

(1)"/." 表示本级目录,可直接忽略

(2)"/.." 表示返回上一级目录,即若上一级目录存在,连同"/.."一并删除,否则只删除/..

(3)若去除冗余后路径为空,返回"/"

(4)若包含连续"/",删除多余的

(5)若路径不是单个“/”,删除路径最后一个“/”

分析:一开始用逐个字符判断的方法,考虑很多边界条件。后来用字符串分割的思想,比较简明。思路如下:

(1)用“/”分割字符串,遍历每个分割部分,存入一个vector<string>中

(2)若当前分割部分为空,证明有连续的"/"或是最后一个“/”,忽略

(3)若当前部分为“.”,忽略

(4)若当前部分为“..”,若vector不为空,去除vector最后一个元素

(5)再将vector中的string用“/”连起来,得到结果

 

C++实现代码:

#include<iostream>
#include<vector>
#include<string>
#include<sstream>
using namespace std;

class Solution
{
public:
    string simplifyPath(string path)
    {
        if(path.empty())
            return "";
        vector<string> ret;
        string tmp;
        stringstream ss(path);
        while(getline(ss,tmp,'/'))
        {
            if(tmp.empty()||tmp==".")
                continue;
            if(tmp=="..")
            {
                if(!ret.empty())
                    ret.pop_back();
            }
            else
                ret.push_back(tmp);
        }
        tmp.clear();
        for(int i=0; i<(int)ret.size(); i++)
        {
            tmp+="/";
            tmp+=ret[i];
        }
        if(ret.empty())
            return "/";
        return tmp;
    }
};

int main()
{
    Solution s;
    string ss="";
    cout<<s.simplifyPath(ss)<<endl;
}

 第二遍

class Solution {
public:
    string simplifyPath(string path)
    {
        if(path.empty())
            return "";
        string res="/";
        vector<string> vec;
        istringstream ss(path);
        string tmp;
        while(getline(ss,tmp,'/'))
        {
            if(tmp.empty()||tmp==".")
                continue;
            if(tmp==".."&&!vec.empty())
            {
                vec.pop_back();
                continue;
            }
            else if(tmp!="..")
                vec.push_back(tmp);
        }
        int i=0;
        while(i<vec.size())
        {
            res+=vec[i];
            ++i;
            if(i<vec.size())
                res+='/';
        }
        return res;
    }
};

 

时间: 2024-09-20 08:45:40

Simplify Path的相关文章

Simplify Path:LeetCode

原题链接: http://oj.leetcode.com/problems/simplify-path/ 这道题目是Linux内核中比较常见的一个操作,就是对一个输入的文件路径进行简化.思路比较明确,就是维护一个栈,对于每一个块(以'/'作为分界)进行分析,如果遇到'../'则表示要上一层,那么就是进行出栈操作,如果遇到'./'则是停留当前,直接跳过,其他文件路径则直接进栈即可.最后根据栈中的内容转换成路径即可(这里是把栈转成数组,然后依次添加).时间上不会超过两次扫描(一次是进栈得到简化路径,

[LeetCode]--71. Simplify Path

Given an absolute path for a file (Unix-style), simplify it. For example, path = "/home/", => "/home" path = "/a/./b/../../c/", => "/c" click to show corner cases. Corner Cases: Did you consider the case where

leetcode难度及面试频率

转载自:LeetCode Question Difficulty Distribution               1 Two Sum 2 5 array sort         set Two Pointers 2 Add Two Numbers 3 4 linked list Two Pointers           Math 3 Longest Substring Without Repeating Characters 3 2 string Two Pointers      

LeetCode总结【转】

转自:http://blog.csdn.net/lanxu_yy/article/details/17848219 版权声明:本文为博主原创文章,未经博主允许不得转载. 最近完成了www.leetcode.com的online judge中151道算法题目.除各个题目有特殊巧妙的解法以外,大部分题目都是经典的算法或者数据结构,因此做了如下小结,具体的解题思路可以搜索我的博客:LeetCode题解 题目 算法 数据结构 注意事项 Clone Graph BFS 哈希表 Word Ladder II

LeetCode All in One 题目讲解汇总(持续更新中...)

终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 如果各位看官们,大神们发现了任何错误,或是代码无法通过OJ,或是有更好的解法,或是有任何疑问,意见和建议的话,请一定要在对应的帖子下面评论区留言告知博主啊,多谢多谢,祝大家刷得愉快,刷得精彩,刷出美好未来- 博主制作了一款iOS的应用"Leetcode Meet Me",里面有Leetcode上所有的题目,并且贴上了博主的解法,随时随地都能

【原创】具有path autovivification和conversion功能的JSON库

      研究该 JSON 库的由头是因为目前开发 modb 需要支持 json 解析功能.而发现这个有意思的 项目 的地方正是在开源中国.OSChina 对该库的描述如下:  json.c 是一个小型的 C 语言的 JSON 解析库,支持路径表达式.autovivification, 和 restartable I/O. 而库的作者做了更为丰富的表述(中英对照翻译如下):  ===== json.c is a JSON C library that supports path autoviv

Description Resource Path Location Type Java compiler level does not match the version of the instal

Description Resource Path Location Type Java compiler level does not match the version of the instal 解决办法 在项目上右键Properties->Project Facets,在打开的Project Facets页面中的Java下拉列表中,选择相应版本. 有可能是java1.6 改成java6之类的

android华为手机读取本地文件夹图片获取path路径null,求指导

问题描述 android华为手机读取本地文件夹图片获取path路径null,求指导 android华为手机读取本地文件夹图片获取path路径null,求指导 解决方案 public String getImagePathFromURI(Uri uri) { Cursor cursor = getActivity().getContentResolver().query(uri null null null null); String path = null; if (cursor != null

program-Program &amp;amp;quot;make&amp;amp;quot; is not found in PATH

问题描述 Program "make" is not found in PATH 在eclipse中导入android项目,clean工程时报Program ""make"" is not found in PATH,请问这是什么错?这的make是指哪的make不知道make在哪啊 解决方案 eclipse cdt插件,开发c/c++程序,编译时报错Program ""make"" not found in