标签:
https://leetcode.com/problems/simplify-path/
Given an absolute path for a file (Unix-style), simplify it.
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
"/../"
?"/"
.‘/‘
together, such as "/home//foo/"
."/home/foo"
.解题思路:
1. 用split将path分段
2. 将分段的结果存入list
3. 从list的第二个元素开始,遇到"."和空,删除它;遇到"..",删除它,再删除前一个元素(如果前一个元素>0)。
4. 从头遍历list,组成结果
public class Solution { public String simplifyPath(String path) { String[] strs = path.split("/"); List<String> list = new LinkedList<String>(); for(int i = 0; i < strs.length; i++) { list.add(strs[i]); } //split方法的第一个元素肯定是空,所以从第二个元素开始 for(int i = 1; i < list.size(); i++) { if(list.get(i).equals(".") || list.get(i).length() == 0) { list.remove(i); i--; } if(list.get(i).equals("..")) { list.remove(i); if(i - 1 >= 1) { list.remove(i - 1); i = Math.max(0, i - 2); }else { i--; } } } String result = ""; for(int i = 1; i < list.size(); i++) { result += "/" + list.get(i); } if(result.length() == 0){ result = "/"; } return result; } }
也可以直接借助split后的数组做。
public class Solution { public String simplifyPath(String path) { String[] strs = path.split("/"); //split方法的第一个元素肯定是空,所以从第二个元素开始 for(int i = 1; i < strs.length; i++) { if(strs[i].equals(".") || strs[i].equals("")) { strs[i] = "#"; } if(strs[i].equals("..")) { strs[i] = "#"; int j = i - 1; while(j >= 1 && strs[j].equals("#")) { j--; } if(j >= 1) { strs[j] = "#"; } } } String result = ""; for(int i = 1; i < strs.length; i++) { if(!strs[i].equals(".") && !strs[i].equals("#")) { result += "/" + strs[i]; } } if(result.length() == 0){ result = "/"; } return result; } }
标签:
原文地址:http://www.cnblogs.com/NickyYe/p/4394941.html