《leetCode》:Simplify Path
来源:互联网 发布:高清网络摄像机软件 编辑:程序博客网 时间:2024/06/06 01:39
题目
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".
题目大意:简化路径
思路
字符串处理,由于”..”是返回上级目录(如果是根目录则不处理),因此可以考虑用栈来记录路径名,这里就直接用java来实现,用C由于没有栈结构,可能保存结果稍微要麻烦一点。
无论用什么语言来实现,需要注意几个细节:
重复连续出现的’/’,只按1个处理,即跳过重复连续出现的’/’;
如果路径名是”.”,则不处理;
如果路径名是”..”(返回上级目录),则需要弹栈,如果栈为空,则不做处理;
如果路径名为其他字符串,入栈。
最后,再逐个取出栈中元素(即已保存的路径名),用’/’分隔并连接起来,不过要注意顺序,栈顶元素是路径的最后面。栈顶元素为路径的最前面的字符。
java实现如下:
public class Solution { public String simplifyPath(String path) { if(path==null){ return null; } Stack<String> sk=new Stack<String>(); String []str=path.split("/");//得到的str[0]=""; for(int i=0;i<str.length;i++){ if(str[i].equals("..")){ if(!sk.isEmpty()){//弹出 sk.pop(); } } else if(str[i].equals(".")||str[i].equals("")){}//什么都不做 else { sk.push(str[i]); } } if(sk.isEmpty()){ return "/"; } else{ StringBuffer sb=new StringBuffer(); while(!sk.isEmpty()){ sb.insert(0, "/"+sk.pop()); } return sb.toString(); } }}
1 0
- LeetCode: Simplify Path
- LeetCode Simplify Path
- LeetCode : Simplify Path
- [Leetcode] Simplify Path
- [leetcode] simplify path
- [LeetCode] Simplify Path
- leetcode 100: Simplify Path
- [leetcode]Simplify Path
- [LeetCode]Simplify Path
- [leetCode] Simplify Path
- [leetcode]Simplify Path
- [leetcode] Simplify Path
- [LeetCode] Simplify Path
- leetcode simplify path
- Leetcode: Simplify Path
- LeetCode题解:Simplify Path
- [LeetCode] Simplify Path
- LeetCode Simplify Path
- 黑马程序员——javaSE_反射
- Android 进阶 Fragment 介绍和使用 (二)
- 南大软院大神养成计划--第十三天活动
- 10行代码搞定PHP页面静态化(10 lines of code to get PHP static pages)
- 10-01 到 11-29的项目总结
- 《leetCode》:Simplify Path
- [Sort]希尔排序
- Trie树及其应用
- u盘格式化的格式及分配单元大小
- 测试1129
- hpuoj--校赛--爬楼梯(模拟)
- 周总结
- 一个程序猿成长记:设置select的selected属性
- POJ 2376Cleaning Shifts