LeetCode-Add to List 71. Simplify Path
2017-06-20 22:20
363 查看
问题描述
给定一个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; } }
相关文章推荐
- [leetcode] 64. Minimum Path Sum Add to List
- leetcode 500 Keyboard Row Add to List
- leetcode -day17 Path Sum I II & Flatten Binary Tree to Linked List & Minimum Depth of Binary Tree
- leetcode 21. Merge Two Sorted Lists Add to List
- 【LeetCode】Add to List 606. Construct String from Binary Tree
- 【LeetCode】Add to List 637. Average of Levels in Binary Tree
- [leetcode]500.Keyboard Row Add to List
- LeetCode-Add to List 494. Target Sum
- Leetcode--Add to List 374. Guess Number Higher or Lower
- LeetCode406. Queue Reconstruction by Height Add to List
- Leetcode--Add to List 215. Kth Largest Element in an Array
- [leetcode] Add to List 169. Majority Element
- LeetCode - Add to List 557. Reverse Words in a String III
- 【LeetCode】417. Pacific Atlantic Water Flow Add to List
- leetcode_ Add to List 121. Best Time to Buy and Sell Stock
- Leetcode--Add to List 201. Bitwise AND of Numbers Range
- leetCode_Add to List 206. Reverse Linked List
- leetcode- Add to List 669. Trim a Binary Search Tree
- LeetCode 25 Reverse Nodes in k-Group Add to List (划分list为k组)
- Leetcode--Add to List 371. Sum of Two Integers