LeetCode Simplify Path
LeetCode-solving Simplify Path
Original question
Simplifies the absolute path of the next file in a Unix system.
Note:
The upper-level directory of the root directory or root directory may have multiple separators used at the same time
Example:
Input: path = "/a/./B/.../../c /"
Output: "/c"
Solutions
The stack is used for processing. When a valid character is encountered, the stack is pressed. When the upper directory character "..." is encountered and the stack is not empty, it pops up. Add an empty character to the bottom of the stack to add a root directory at the end of the connection string.
AC Source Code
class Solution(object): def simplifyPath(self, path): """ :type path: str :rtype: str """ parts = path.split("/") result = [''] for part in parts: if part: if part not in ('.', '..'): if len(result) == 0: result.append('') result.append(part) elif part == '..' and len(result) > 0: result.pop() if len(result) < 2: return "/" else: return "/".join(result)if __name__ == "__main__": assert Solution().simplifyPath("/a/./b/../../c/") == '/c' assert Solution().simplifyPath("/home/") == "/home" assert Solution().simplifyPath("/../../") == "/"