题意:

image.png

解题思路:

  1. 思路:
  2. 1. 先进行分割;
  3. 2. ''或者为'.',跳过不处理;=> 为空的情况[/home//foo/]
  4. 3. 当为".."时,如果栈不为空,则pop栈顶;
  5. 4. 当不是上面两种情况时,入栈;
  6. 5. 最后join返回;

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param String $path
  4. * @return String
  5. */
  6. function simplifyPath($path) {
  7. $res = [];
  8. $path = trim($path, '/');
  9. $pathArr = explode('/', $path);
  10. foreach ($pathArr as $k => $v) {
  11. if ($v == '' || $v == '.') continue;
  12. else if ($v == '..') array_pop($res);
  13. else array_push($res, $v);
  14. }
  15. return '/' . implode('/', $res);
  16. }
  17. }

GO代码实现:

  1. func simplifyPath(path string) string {
  2. spath := strings.Split(path, "/")
  3. var stack []string
  4. for i := 0; i < len(spath); i++ {
  5. if spath[i] == "" || spath[i] == "." {
  6. continue
  7. }
  8. if spath[i] == ".." {
  9. if len(stack) > 0 {
  10. stack = stack[0 : len(stack) - 1]
  11. }
  12. } else {
  13. stack = append(stack, spath[i])
  14. }
  15. }
  16. return "/" + strings.Join(stack, "/")
  17. }