当前位置:网站首页>Leetcode: push domino (domino simulation)

Leetcode: push domino (domino simulation)

2022-06-24 22:36:00 Review of the white speed Dragon King

 Insert picture description here
Ideas :
Find both sides left and right, The leftmost can be set to L, The rightmost is set to R, No effect
If in the same direction , Then the middle is reversed in the same direction
If reverse and cohesive , In the middle
Then continue the double pointer traversal left and right that will do

src

class Solution:
    def pushDominoes(self, dominoes: str) -> str:
        # I little interesting 
        n = len(dominoes)
        s = list(dominoes)
        #  On the left is 'L' No effect 
        left = 'L'
        right = '.'
        i = 0
        while i < n:
            j = i
            #  A continuous segment has not been pushed 
            while j < n and s[j] == '.':
                j += 1
            #  Find the one on the right ,  On the far right R No effect 
            right = s[j] if j < n else 'R'
            #  If the two directions are the same , Then the middle domino goes in the same direction 
            if left == right:
                while i < j:
                    s[i] = right
                    i += 1
            #  If the directions are opposite 
            elif left == 'R' and right == 'L':
                k = j - 1
                while i < k:
                    s[i] = 'R'
                    s[k] = 'L'
                    i += 1
                    k -= 1
            left = right
            i = j + 1
        return ''.join(s)

summary :
Double pointer simulation , Introduction of default directions on both sides

原网站

版权声明
本文为[Review of the white speed Dragon King]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211232152117.html