1662. Check If Two String Arrays are Equivalent

Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.

A string is represented by an array if the array elements concatenated in order forms the string.

My Answer 1: Accepted (Runtime: 24 ms - 96.38% / Memory Usage: 14.3 MB - 30.92%)

class Solution:
    def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
        w1 = ''.join(word1)
        w2 = ''.join(word2)
        
        if w1 == w2:
            return True
        
        return False

둘다 스트링으로 만들어서 비교

join 아니었으면 word1, word2 다 훑으면서 string 에 더해주고 비교했을듯

아니면 포인터 4개 써서 한글자씩 비교하다가 다른 글자 나오면 False return


236. Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

My Answer 1: Accepted (Runtime: 72 ms - 67.75% / Memory Usage: 27.7 MB - 23.64%)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        # 이거 왜 푼 기억이 없지..
        
        def func(root):
            if root is None:
                return 0
            
            cnt = 0
            
            cnt += func(root.left)
            cnt += func(root.right)
            
            if root.val == p.val or root.val == q.val:
                cnt += 1
            
            if cnt == 2:
                self.ans.left = root
                cnt = 0
            
            return cnt
        
        self.ans = TreeNode(0)
        func(root)
        
        return self.ans.left

처음엔 value 값만 return 하는 줄 알고
p, q 각각의 루트들을 리스트에 저장해서
리스트를 비교해서 LCA 찾기 했는데 노드를 return 해야함...

그래서 post-order 로 자식 노드들을 먼저 보면서
p, q 를 자식으로 갖는 (cnt == 2) 노드를 찾아서 self.ans.left 에 넣어줌

루션이가 오히려 이해하기 어렵네요...

profile
Hello, World!

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN