题意:
解题思路:
思路:
1. 先进行分割;
2. 为''或者为'.',跳过不处理;=> 为空的情况[/home//foo/]
3. 当为".."时,如果栈不为空,则pop栈顶;
4. 当不是上面两种情况时,入栈;
5. 最后join返回;
PHP代码实现:
class Solution {
/**
* @param String $path
* @return String
*/
function simplifyPath($path) {
$res = [];
$path = trim($path, '/');
$pathArr = explode('/', $path);
foreach ($pathArr as $k => $v) {
if ($v == '' || $v == '.') continue;
else if ($v == '..') array_pop($res);
else array_push($res, $v);
}
return '/' . implode('/', $res);
}
}
GO代码实现:
func simplifyPath(path string) string {
spath := strings.Split(path, "/")
var stack []string
for i := 0; i < len(spath); i++ {
if spath[i] == "" || spath[i] == "." {
continue
}
if spath[i] == ".." {
if len(stack) > 0 {
stack = stack[0 : len(stack) - 1]
}
} else {
stack = append(stack, spath[i])
}
}
return "/" + strings.Join(stack, "/")
}