leetcode【第十二周】简化路径

问题描述:

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值