LeetCode-Add to List 71. Simplify Path
来源:互联网 发布:网络应用层协议有哪些 编辑:程序博客网 时间:2024/06/09 22:31
问题描述
- 给定一个Unix绝对路径,简化该路径并返回。
- 例如:path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
解题思路
利用栈来求解,从最左边开始依次取出两个/ /之间的字符串,如果该字符串是“..”,则在栈中弹出一个路径字符串;如果该字符串是“.”或者“”,栈保持不变;否则,将字符串压栈。然后再全部弹出组成新的路径。
代码
import java.util.Stack;public class Solution { public String simplifyPath(String path) { if(path==null || path.length()==0) return ""; Stack<String> stack=new Stack<String>(); int first=path.indexOf("/"); int second=0; while(path.length()>0){ second=path.indexOf("/",first+1); if(second==-1) second=path.length(); String tem=path.substring(first+1,second); path=path.substring(second,path.length()); if(tem.equals("..")){//比较两个字符串是否相等一定是equals而不是==!! if(!stack.empty()) stack.pop(); }else if(tem.equals(".") || tem.equals("")) continue; else{ stack.push("/"+tem); } first=0; } String result=""; if(stack.empty()) return "/"; while(!stack.empty()) result=stack.pop()+result; return result; }}
因为是函数的输入是绝对路径,因此字符串必然是从“/”开始,因此可以让first变量恒为0.如下所示:
import java.util.Stack;public class Solution { public String simplifyPath(String path) { if(path==null || path.length()==0) return ""; Stack<String> stack=new Stack<String>(); //int first=path.indexOf("/"); int second=0; while(path.length()>0){ second=path.indexOf("/",0+1); if(second==-1) second=path.length(); String tem=path.substring(0+1,second); path=path.substring(second,path.length()); if(tem.equals("..")){ if(!stack.empty()) stack.pop(); }else if(tem.equals(".") || tem.equals("")) continue; else{ stack.push("/"+tem); } //first=0; } String result=""; if(stack.empty()) return "/"; while(!stack.empty()) result=stack.pop()+result; return result; }}
阅读全文
0 0
- LeetCode-Add to List 71. Simplify Path
- LeetCode 112. Path Sum Add to List
- LeetCode 71. Simplify Path
- LeetCode --- 71. Simplify Path
- [Leetcode] 71. Simplify Path
- [leetcode] 71.Simplify Path
- [leetcode] 71.Simplify Path
- Leetcode 71. Simplify Path
- LeetCode 71. Simplify Path
- Leetcode 71. Simplify Path
- 71. Simplify Path LeetCode
- leetcode 71. Simplify Path
- LeetCode 71. Simplify Path
- LeetCode 71. Simplify Path
- Leetcode 71. Simplify Path
- [leetcode] 71. Simplify Path
- LeetCode 71. Simplify Path
- LeetCode - 71. Simplify Path
- TUM数据集测评工具的使用
- eclipse 创建maven web项目
- PAT(B)_1037. 在霍格沃茨找零钱(20)
- laravel(六)-Blade模板
- ckeditor上传图片时与后端的csrfToken验证
- LeetCode-Add to List 71. Simplify Path
- React-Native中的Text
- [模板]KMP算法
- spring boot mybatis打印sql
- Nginx实现虚拟主机 练习总结2017-6-20
- Glide类似You cannot start a load for a destroyed activity异常简单分析
- 51 WebGL切换着色器
- java异常捕获的一点感悟
- Longest Increasing Subsequence