71. Simplify Path
class Solution { public String simplifyPath(String path) { Deque<String> stack = new LinkedList<>(); Set<String> set = new HashSet<>(Arrays.asList("",".", "..")); for( String element: path.split("/")){ if(!set.contains(element)){ stack.push(element); }else if(element.equals("..") && !stack.isEmpty()){ stack.pop(); } } if (stack.isEmpty()){ return "/"; } String result = ""; for(String element: stack){ result = "/" + element + result; } return result; } }
“..” Means go up a level, so delete the prev
“.” Means do nothing
“” Means do nothing
First, we need to split the input by the splitter “/”
这种方式Arrays.asList 又见到了,
Set<String> set = new HashSet<>(Arrays.asList("",".", ".."));
When we pop stack. Need to check if the stack is empty or not
If it’s not empty , we pop
After done traversing the input, we need to return the things stored in the
Stack
If the stack is empty, return “/”
If the stack is not empty, we format the things in the stack by the splitter “/”
加结果的时候是这样加的, 加上之前的
result = "/" + element + result;
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".
posted on 2018-07-18 13:07 猪猪🐷 阅读(118) 评论(0) 收藏 举报
浙公网安备 33010602011771号