[Mock] Facebook 2

shsh·2021년 3월 26일
0

Mock

목록 보기
14/93

71. Simplify Path

Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path.

In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods such as '...' are treated as file/directory names.

The canonical path should have the following format:

The path starts with a single slash '/'.
Any two directories are separated by a single slash '/'.
The path does not end with a trailing '/'.
The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..')
Return the simplified canonical path.

My Answer 1: Wrong Answer (193 / 256 test cases passed.)

class Solution:
    def simplifyPath(self, path: str) -> str:
        result = ["/"]
        
        i = 1
        while i < len(path):
            # 슬래시 여러개일 때 제외
            if path[i] == "/" and result[-1] != "/":
                cnt = 0
                # 점의 개수가 2개 이상이면 무조건 상위로 가야하는 줄 알고 상위 디렉토리까지 pop 하도록 함
                # => "/..." 인 경우도 있더라..^^ (이때는 파일 이름처럼 여겨지는 듯)
                while result[-1] == ".":
                    cnt += 1
                    result.pop()
                if cnt > 1:
                    if len(result) > 2:
                        result.pop()
                        while result[-1] != "/":
                            result.pop()
                if result[-1] != "/":
                    result.append(path[i])
            # 문자와 점들을 저장
            elif path[i] != "/":
                result.append(path[i])
            i += 1
        
        # 혹시 마지막이 슬래시면 pop
        if result[-1] == "/" and len(result) > 2:
            result.pop()
        
        result = ''.join(result)
        
        return result

첨에 문제 이해를 잘못해서 엉망됐네요...^^

  1. 상위 디렉토리로 이동한다는 생각을 안함 -> 뒤늦게 깨닫기
  2. 점의 개수가 2개 이상이면 무조건 상위로 가야하는 줄 앎 -> 막판에 알았네요

stack 을 써서 경로를 쭉 넣어주고 마지막에 join 으로 합쳐서 문자열로 반환


270. Closest Binary Search Tree Value

Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target.

My Answer 1: Accepted (Runtime: 40 ms - 68.03% / Memory Usage: 16.2 MB - 12.77%)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def closestValue(self, root: TreeNode, target: float) -> int:
        # m = target 과의 차이값 중 최솟값
        def traversal(m, root):
            if root is None:
                pass
            
            if root.val == target:
                m = 0
                self.result = root.val
                return
            
            elif root.val < target:   # target 보다 작으면 오른쪽으로 가서 큰 값 보기
                if m > abs(target-root.val):
                    m = abs(target-root.val)
                    self.result = root.val
                if root.right:
                    traversal(m, root.right)

            elif root.val > target:   # target 보다 크면 왼쪽으로 가서 작은 값 보기
                if m > abs(target-root.val):
                    m = abs(target-root.val)
                    self.result = root.val
                if root.left:
                    traversal(m, root.left)
        
        m = float('inf')
        self.result = 0
        traversal(m, root)
        
        return self.result

이거는 abs(target-root.val) 구해서 차이값 비교함

profile
Hello, World!

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN