71. Simplify Path
2016-06-04 23:13
274 查看
Given an absolute path for a file (Unix-style), simplify it.
For example,
path =
path =
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
such as
In this case, you should ignore redundant slashes and return
维护一个栈,用以存储路径!
可以以字符 ' / ' 作为分隔符,把路径分开,分开以后的数组中可能会有以下几种情况:
1. 是 " . ",表示当前路径,是冗余的,直接忽略即可。
2. 是 “..” 表示上一级目录,这时候如果栈不空就POP ,表示抛弃当前目录,进入上一层目录。
3. 是 “” ,即空字符,这表明两个 ’ / ‘ 挨在了一起,也是冗余的,直接忽略。
4. 是除了以上之外的字符,这时候表示目录名称,把字符入栈。
最后重建路径,如果栈空,就输出根目录,如果不空,输出重建的路径。
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".
维护一个栈,用以存储路径!
可以以字符 ' / ' 作为分隔符,把路径分开,分开以后的数组中可能会有以下几种情况:
1. 是 " . ",表示当前路径,是冗余的,直接忽略即可。
2. 是 “..” 表示上一级目录,这时候如果栈不空就POP ,表示抛弃当前目录,进入上一层目录。
3. 是 “” ,即空字符,这表明两个 ’ / ‘ 挨在了一起,也是冗余的,直接忽略。
4. 是除了以上之外的字符,这时候表示目录名称,把字符入栈。
最后重建路径,如果栈空,就输出根目录,如果不空,输出重建的路径。
public static String simplifyPath(String path) { int len=path.length(); int[] indexarr=new int[len]; int cnt=0; for(int i=0;i<len;i++) if(path.charAt(i)=='/') indexarr[cnt++]=i; String[] sarr; if(indexarr[cnt-1]<len-1) sarr=new String[cnt]; else { sarr=new String[cnt-1]; } for(int i=0;i<cnt-1;i++) sarr[i]=path.substring(indexarr[i]+1, indexarr[i+1]); if(indexarr[cnt-1]<len-1) sarr[cnt-1]=path.substring(indexarr[cnt-1]+1); Stack<String> stack=new Stack<>(); for(int i=0;i<sarr.length;i++) { if(sarr[i].compareTo("..")==0) { if(!stack.isEmpty()) stack.pop(); } else if(sarr[i].compareTo(".")==0||sarr[i].compareTo("")==0); else { stack.push(sarr[i]); } } if(stack.isEmpty()) return "/"; StringBuilder sb=new StringBuilder(); sb.append('/'); for(String ss:stack) { sb.append(ss); sb.append('/'); } sb.deleteCharAt(sb.length()-1); return sb.toString(); }
相关文章推荐
- Class.forName()用法详解
- 加速度传感器的原理和应用-手机翻转、失重检测、运动检测、位置识别
- 121. Best Time to Buy and Sell Stock
- JavaScript快速学习
- Android带Library项目的导入过程
- JAXP SAX模式解析xml文档
- Centos7 搭建Redis3.2.0版本集群环境
- 加密算法比较3DES AES RSA ECC MD5 SHA1等
- 物联网网络编程、Web编程综述
- DOM4j 解析xml文档,完成增删改查
- UNIX网络编程 第一章
- Spring学习(十三)Spring Bean 的命名方式介绍
- Trie
- 两款JSON类库Jackson与JSON-lib的性能对比
- 蓝牙(BLE)应用框架接口设计和应用开发——以TI CC2541为例
- 从零开始搭建微信硬件开发环境全过程——1小时掌握微信硬件开发流程
- 二分思路总结
- WebService 的缓存机制
- POJ 2688 Cleaning Robot
- Picasso入门教程(八)通过Tag()来管理图片