LeetCode刷题实战71:简化路径
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 简化路径,我们先来看题面:
https://leetcode-cn.com/problems/simplify-path/
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level.
Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.
题意
示例 1:
输入:"/home/"
输出:"/home"
解释:注意,最后一个目录名后面没有斜杠。
示例 2:
输入:"/../"
输出:"/"
解释:从根目录向上一级是不可行的,因为根是你可以到达的最高级。
示例 3:
输入:"/home//foo/"
输出:"/home/foo"
解释:在规范路径中,多个连续斜杠需要用一个斜杠替换。
示例 4:
输入:"/a/./b/../../c/"
输出:"/c"
示例 5:
输入:"/a/../../b/../c//.//"
输出:"/c"
示例 6:
输入:"/a//b////c/d//././/.."
输出:"/a/b/c"
解题
4.1 如果是连续的"/", i++ , j=i;
4.2 如果指针j指向非"/", 持续右移j
4.3 j将停留的位置要么是path遍历结束, 要么是"/"
4.3.1 如果j将path遍历结束, 可以直接substring(i,j)
4.3.2 如果j停留在"/"处, 也可以直接substring(i,j)
4.4 比较substring(i,j) == "..", 栈弹出,相当于回到上一层目录
4.5 比较substring(i,j) == ".", 让i指向j指向的"/", 否则, 表示substring(i,j)是一个合法目录,将其压栈
5.1 所有路径以"/"开始, 因此i,j指针下标从1开始
5.2 遇到".."时, 需要保证栈不为空
5.3 遇到非".", ".."时, 才需要压栈
5.4 所有情况都需要将i更新为j, 让i始终指向分界字符 "/"
class Solution {
public String simplifyPath(String path) {
if(path == null || path.length() < 1) return path;
Stackstk = new Stack();
// 主要是边界问题
for(int i = 1, j = 1; i < path.length(); i++, j = i){
if(path.charAt(i-1) == '/' && path.charAt(i) == '/') { continue;}
while(j < path.length() && path.charAt(j) != '/') j++;
String tmp = path.substring(i, j);
if("..".equals(tmp) && stk.size() > 0){
stk.pop();
}else if(!".".equals(tmp) && !"..".equals(tmp)){
stk.push(tmp);
}
i = j;
}
if(stk.size() == 0) return "/";
StringBuilder sb = new StringBuilder();
while(stk.size() > 0){
sb.insert(0, "/"+stk.pop());
}
return sb.toString();
}
}
上期推文: