leetcode解题方案--071--Simplify Path
2017-12-31 00:23
447 查看
题目
Given an absolute path for a file (Unix-style), simplify it.For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
分析
两个句点为返回。设计一个栈,如果遇到返回就弹出。
如果遇到一个句点就忽略
然后把栈一一弹出,弹出时要在已有字符串最前面插入。
如果为空,则只加一个/
class Solution { public static String simplifyPath(String path) { String [] xx = path.split("/"); Stack<String> stack = new Stack<String>(); for (int i = 0; i<xx.length; i++) { if (xx[i].length() ==0 || xx[i] .equals(".")) { continue; } if (xx[i].equals("..")) { if (!stack.empty()) { stack.pop(); } } else { stack.push(xx[i]); } } StringBuffer xxx = new StringBuffer(""); while (!stack.empty()) { xxx.insert(0, stack.pop()); xxx.insert(0,"/"); } if (xxx.length() == 0) { xxx.append("/"); } return xxx.toString(); } }
相关文章推荐
- leetcode解题方案--053--Maximum Subarray
- leetcode解题方案--060--Permutation Sequence
- leetcode解题方案--066--Plus One
- [LeetCode] Simplify Path 解题报告
- leetcode解题方案--073--set matrix zeroes
- leetcode解题方案--167--Two Sum II - Input array is sorted
- 【LeetCode】Simplify Path 解题报告
- leetcode解题方案--051--N-Queens
- leetcode解题方案--055--jumpGame
- leetcode解题方案--056--Merge Intervals
- leetcode解题方案--062--Unique Paths
- leetcode解题方案--067--Add Binary
- leetcode解题方案--021--Merge Two Sorted Lists
- leetcode解题方案--042--Trapping Rain Water
- leetcode解题方案--057--Insert Interval
- LeetCode71 Simplify Path 解题报告
- leetcode解题方案--074--Search a 2D Matrix
- leetcode解题方案--034--Search for a Range
- leetcode解题方案--043-- Multiply Strings
- leetcode解题方案--047--Permutations II