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"
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. 用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; } }
update 2015/05/28:
二刷,用stack。
1. 将s按照“/”进行split。
2. 遍历split[]。
3. 遇到..,如果stack非空,弹出栈顶。stack空,不动。
4. 遇到.,不动。
5. 遇到其他(其实就是字母),push进stack。
6. split[]遍历结束后,依次弹出stack中的元素,连接“/”,放在res最前面。
7, 返回res。
public class Solution { public String simplifyPath(String path) { String[] split = path.split("/"); String res = new String(); Stack<String> stack = new Stack<String>(); for(int i = 0; i < split.length; i++) { if(split[i].length() == 0) { continue; } if(split[i].equals("..")) { if(stack.size() > 0) { stack.pop(); } } else if(!split[i].equals(".")) { stack.push(split[i]); } } while(stack.size() > 0) { res = "/" + stack.peek() + res; stack.pop(); } if(res.length() == 0) { return "/"; } return res; } }