LeetCode Simplify Path

Source: Internet
Author: User

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("/../../") == "/"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.