【leetcode】Simplify Path

33 篇文章 0 订阅
10 篇文章 0 订阅

链接:https://oj.leetcode.com/submissions/detail/9774025/


描述:

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


解法:

本体对细节及边界考虑研究较高。

下面是我看到的一个比较好的解法描述(直接引过来):

面对这种题目一定要保持清醒,先分析好题目之后再开始码代码。

题目的要求是输出Unix下的最简路径,Unix文件的根目录为"/","."表示当前目录,".."表示上级目录。

例如:

输入1:

/../a/b/c/./.. 

输出1:

/a/b

模拟整个过程:

1. "/" 根目录

2. ".." 跳转上级目录,上级目录为空,所以依旧处于 "/"

3. "a" 进入子目录a,目前处于 "/a"

4. "b" 进入子目录b,目前处于 "/a/b"

5. "c" 进入子目录c,目前处于 "/a/b/c"

6. "." 当前目录,不操作,仍处于 "/a/b/c"

7. ".." 返回上级目录,最终为 "/a/b"


我用一个堆栈来模拟路径的行为,遇到"."不操作,遇到".."退栈,其他情况都压入堆栈。

P.S.

有以"."开头的路径,例如:"/.fdfd"。


实现中用到一个小技巧在path后面加一个‘/',不用单独处理最后一个情况。

代码实现如下:

  string simplifyPath(string path) {
    	if( path.size() == 0 ) return "/";
    	path += "/";
    	int len = path.size();
    	int start = 1;
    	stack<string> s;
    
    	while( start < len)
    	{
    		int end = start;
    		while( path[end] != '/')
    			end++;
    		if( start == end ){
    			start++;
    			continue;
    		}
    		string str = path.substr(start, end-start);
    		if( str[0] == '.' && str.length() == 2 && str[1] == '.'){
    			if( !s.empty())
    				s.pop();
    		}else if( !(str[0] == '.' && str.length() == 1 )){
    			s.push(str);
    		}
    		start = end + 1;
    	}
    
    	if( s.empty()) return "/";
    	string result;
    	while( !s.empty() )
    	{
    		result = "/"+s.top()+ result;
    		s.pop();
    	}
    	return result;
    }


参考自:http://blog.csdn.net/pickless/article/details/9969581

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值