Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 71 · Stack Simulation / String Processing

Simplify Path

LeetCode 71 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Stack of directory names.

మధ్యస్థంStringStack
LeetCode లో తెరవండి ↗

నేను Simplify Path (LeetCode 71) ను ఇలా పరిష్కరించాను — Stack Simulation / String Processing ప్యాటర్న్‌లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

Split the path on '/' and process the pieces with a stack: '..' pops a directory, '.' and empty pieces do nothing, anything else is a directory name to push.

Approach

  1. 1

    Split by '/'.

  2. 2

    Skip '' and '.'.

  3. 3

    '..' → pop if possible.

  4. 4

    Push other names; join with '/' and prefix '/'.

నేను ఎలా పరిష్కరించాను

Stack of componentsPythonO(n) time
class Solution:
    def simplifyPath(self, path: str) -> str:
        #/.../a/../b/c/../d/./
        #/directory_name/ [a/..] - >/directory_name/
        #/directory_name/b/c/.. ->/directory_name/b/
        #/directory_name/b/d/. -> /.../b/d

        #intuition is - 
        #/d/./ -> /d
        #if it's single dot (.) we just ignoring . and taking the previous path /d
        #/user/Documents/.. ->/user
        #if it's a double dot then we are removing Documents

        #approach
        #have a stack
        #split string by /
        #if cur string is . no need to do anything
        #if cur string is .. pop from stack
        #rest - add to stack
        #finally join by / and return 
        stack =[]
        components = path.split("/")
        for component in components:
            if component=="." or component=="":
                continue
            elif component=="..":
                if len(stack)>0:
                    stack.pop()
            else:
                stack.append(component)
        return "/"+"/".join(stack)
స్టెప్-త్రూ లోడ్ అవుతోంది…

Simplify Path — తరచూ అడిగే ప్రశ్నలు

Simplify Path వెనుక ఉన్న intuition ఏమిటి?

Split the path on '/' and process the pieces with a stack: '..' pops a directory, '.' and empty pieces do nothing, anything else is a directory name to push.

Simplify Path (LeetCode 71) ను ఎలా పరిష్కరించాలి?

1. Split by '/'. 2. Skip '' and '.'. 3. '..' → pop if possible. 4. Push other names; join with '/' and prefix '/'.

Simplify Path యొక్క time, space complexity ఎంత?

Time: O(n). Space: O(n). (Accepted approach: Stack of components.)

Simplify Path లో సాధారణ పొరపాట్లు ఏమిటి?

'...' is a valid directory name, not a parent reference.