Simplify Path——LeetCode
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
题目大意:给一个String,表示一个文件的绝对路径,简化它。
解题思路:用一个栈表示即可,..向上返回一层,就是出栈一个元素,.不做操作,其他的入栈。
public class Solution { public String simplifyPath(String path) { if (path == null || path.length() == 0) { return null; } Deque<String> deque = new ArrayDeque<>(); String[] dirs = path.split("/"); for (String dir : dirs) { if (".".equals(dir)){ continue; } else if ("..".equals(dir)) { if (!deque.isEmpty()) { deque.pop(); } } else { if(dir==null||dir.length()==0){ continue; } deque.push(dir); } } String res = "/"; while (!deque.isEmpty()) { res += deque.pollLast(); res += "/"; } res = res.substring(0, res.length() > 1 ? res.length() - 1 : 1); return res; } }