Swift solution - Stack


  • 0
    class Solution {
        func simplifyPath(_ path: String) -> String {
            var stack = [String]()
            var result = ""
            
            for dir in path.components(separatedBy: "/") {
                if dir == ".." && !stack.isEmpty {
                    stack.removeLast()
                } else if !["..", ".", ""].contains(dir) {
                    stack.append(dir)
                }
            }
            for dir in stack {
                result += "/" + dir
            }
            
            return result.isEmpty ? "/" : result
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.