Simplify Path
LeetCode 71 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Stack of directory names.
ನಾನು 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
Split by '/'.
- 2
Skip '' and '.'.
- 3
'..' → pop if possible.
- 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.