< All posts

2337. Move Pieces to Obtain a String

๋ฌธ์ œ ์„ค๋ช…

์ด ๋ฌธ์ œ๋Š” 'L', 'R', '_'๋กœ ์ด๋ฃจ์–ด์ง„ ๋‘ ๋ฌธ์ž์—ด์ด ์ฃผ์–ด์งˆ ๋•Œ, ๋‹ค์Œ ์—ฐ์‚ฐ์„ ํ†ตํ•ด ๋‘ ๋ฌธ์ž์—ด์ด ๋˜‘๊ฐ™์•„์งˆ ์ˆ˜ ์žˆ๋Š”์ง€ ํ™•์ธํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

  • 'L' ์™ผ์ชฝ์— '_'๊ฐ€ ์žˆ๋‹ค๋ฉด, 'L'์€ ์™ผ์ชฝ์œผ๋กœ ํ•œ ์นธ ์ด๋™
  • 'R' ์˜ค๋ฅธ์ชฝ์— '_'๊ฐ€ ์žˆ๋‹ค๋ฉด, 'R'์€ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ํ•œ ์นธ ์ด๋™

2337

ํ’€์ด ๋ฐ ํ•ด์„ค

ํ’€์ด

class Solution:
    def canChange(self, start: str, target: str) -> bool:
        # if order is different return False
        if start.replace('_', '') != target.replace('_', ''):
            return False
        
        n = len(start)
        i = j = 0

        while i < n and j < n:
            # skip underscores at start
            while i < n and start[i] == '_':
                i += 1
            while j < n and target[j] == '_':
                j += 1
            
            # if exhausted, they should both be equal
            if i == n or j == n:
                return i == j
            
            # check if pieces match 
            if (start[i] != target[j]) or \
                (start[i] == 'L' and i < j) or \
                (start[i] == 'R' and i > j):
                return False
            
            i += 1
            j += 1
        
        return True

Complexity Analysis

tc

์‹œ๊ฐ„ ๋ณต์žก๋„

  • O(N) : N์€ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด์ด๋‹ค.

๊ณต๊ฐ„ ๋ณต์žก๋„

  • O(1) : ์ถ”๊ฐ€์ ์ธ ๊ณต๊ฐ„์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค.

Constraint Analysis

Constraints:
n == start.length == target.length
1 <= n <= 105
start and target consist of the characters 'L', 'R', and '_'.

References

ยฉ 2025 HyunJoon Sung. All Rights Reserved.

GitHub