leetcode【第十二周】简化路径

来源:互联网 发布:linux服务器ftp服务开 编辑:程序博客网 时间:2024/06/15 14:36

问题描述:

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

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

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

问题分析:

这是一个模拟Unix系统下路径转化的问题,把有复杂相对路径转化为简单直接的绝对路径。可以通过字符是否是"/"来记录和移动下标,从而逐段逐段地截取输入路径的内容。同样,我们知道,对于文件的访问类似于一个栈的结构,当读到一个目录名就进展,遇到“..”就是回退到上一级目录,就是说将当前顶部的文件名出栈。因为我们可以对我们逐段截取到的字符串来做判断,若是“.”,则不做处理,若不等于“..”则是文件夹名,将它入栈【这里我们采用一个字符串数组来存放】,若是"..",则将栈顶元素出栈,相当于返回一级目录。一次类推,即可得到正确且简洁的文件夹访问顺序。当输出路径时,若栈中无文件夹名存在【即在当前目录】,则返回“/”。具体的实现代码如下。

代码如下:


class Solution {public:string simplifyPath(string path) {vector tmp;int index = 0;while (index < path.length()-1){while (path[index] == '/'&&index < path.length())index++;int start = index;while (path[index] != '/'&&index < path.length())index++;int end = index-1;string con = path.substr(start,end-start+1);cout << con << endl;if (con == ".."){if (!tmp.empty())tmp.pop_back();}else if (con != "."){tmp.push_back(con);}}string res;for (vector::iterator iter = tmp.begin(); iter != tmp.end(); iter++){if (*iter != "\0"){res += "/";res += *iter;}}if(res=="")    return "/";else    return res;}};

0 0
原创粉丝点击