LC.838. Push Dominoes

LC.838. Push Dominoes_第1张图片
LC.838. Push Dominoes_第2张图片

class Solution(object):
    def pushDominoes(self, dominoes):
        """
        left right两个指针交替更新,确定位置后再进行推倒操作
        注意右边界是否要更新
        开始时将dominoes首位添加L 和R以方便计算
        """
        dominoes = "L" + dominoes + "R"
        # 注意这里right初始值为0
        left, right = 1, 0
        dominoes = list(dominoes)
        no_update_right = False
        while(right < len(dominoes)):
            if no_update_right is False:
                right += 1
                while (right < len(dominoes) and dominoes[right] == "."):
                    right += 1

            left = right
            right = right+1

            while(right < len(dominoes) and dominoes[right] == "."):
                right += 1

            if left == len(dominoes)-1:
                break

            print(left,right)
            if dominoes[left] == "R" and dominoes[right] == "L":
                left_index, right_index = left, right
                while(left_index < right_index):
                    dominoes[left_index] = "R"
                    dominoes[right_index] = "L"
                    left_index, right_index = left_index+1, right_index-1
                no_update_right = False

            elif dominoes[left] == "R" and dominoes[right] == "R":
                left_index = left
                while(left_index <= right):
                    dominoes[left_index] = "R"
                    left_index += 1
                no_update_right = True

            elif dominoes[left] == "L" and dominoes[right] == "R":
                left_index= left - 1
                while(dominoes[left_index] == "."):
                    dominoes[left_index] = "L"
                    left_index -= 1
                no_update_right = True

            else:
                left_index, right_index = left-1, right-1
                while(dominoes[left_index] == "."):
                    dominoes[left_index] = "L"
                    left_index -= 1
                while(dominoes[right_index] == "."):
                    dominoes[right_index] = "L"
                    right_index -= 1
                no_update_right = False

        return "".join(dominoes[1:-1])

你可能感兴趣的:(LeetCode)