LeetCode happy brush title forty-eight days --71. Simplify Path

71. Simplify Path
Medium

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. For more information, see: Absolute path vs relative path in Linux/Unix

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.

 

Example 1:

Input: "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.

Example 2:

Input: "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.

Example 3:

Input: "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.

Example 4:

Input: "/a/./b/../../c/"
Output: "/c"

Example 5:

Input: "/a/../../b/../c//.//"
Output: "/c"

Example 6:

The INPUT: " /a//b////c/d//./.// .." 
the Output: " / A / b / c" 

clarify the rules is important, in short, experience The representative of the current layer, ignored. .. on the floor, the stack has been cleared, the remaining characters are normal path, but began to have / middle / only one
Python problem is that no package of classes on their own to achieve this, Further achieve segmentation / function in Python
class Solution(object):
    def simplifyPath(self, path):
        """
        :type path: str
        :rtype: str
        """
        # define stack
        stack=list()
        # split string
        path=[p for p in path.split('/') if p]
        for p in path:
            if p == '.':
                continue
            elif p == '..':
                if stack:
                    stack.pop()
            else:
                stack.append(p)
        return '/'+'/'.join(stack)

Solu=Solution()
path="/a/./b/../../c/"
print(Solu.simplifyPath(path))
 
 

BONUS:

1. There may be multiple / situation occur, the direct use of split division, will lead to an empty string, the solution is, with judgment statement. In the cycle directly added to the stack in

2.

Python join () method is used to specify the elements of a sequence is connected to generate a new character string.

grammar

join () method syntax:

str.join(sequence)

 

 

Guess you like

Origin www.cnblogs.com/Marigolci/p/11616379.html