반응형
https://leetcode.com/problems/move-pieces-to-obtain-a-string
문자열을 다뤄본 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
_는 이동할 수 있는 공간 즉, 비어 있으므로 고려할 필요 없습니다. 만들어야되는 'L', 'R'의 index를 함께 배열 start_idx_char, target_idx_char를 선언해 저장합니다.
📔 풀이과정
1. start_idx_char과 target_idx_char의 길이가 다르다면 이동해서 target을 만들 수 없으므로 False를 반환합니다.
2. 빈 공간을 제거했는데 start의 'L', 'R'배치와 target의 'L', 'R'배치의 순서가 다르다면 만들 수 없으므로 False를 반환합니다.
3. 같은 길이와 순서를 가진 start_idx_char과 target_idx_char의 원소를 순회하며 다음을 검사합니다.
3-1. start의 'L'은 현재 index값에서 왼쪽으로 밖에 이동할 수 없습니다. target의 index가 더 크다면 이동이 불가하므로 False를 반환합니다.
3-2. start의 'R'은 현재 index값에서 오른쪽으로 밖에 이동할 수 없습니다. target의 index가 더 작다면 이동이 불가하므로 False를 반환합니다.
📔 정답 출력 | 반환
모든 검사를 완료 후 True를 반환합니다.
📕 Code
📔 Python3
from bisect import bisect_left
class Solution:
def canChange(self, start: str, target: str) -> bool:
start_char_idx = [(i,char) for i,char in enumerate(start) if char != '_']
target_char_idx = [(i,char) for i,char in enumerate(target) if char != '_']
if len(start_char_idx) != len(target_char_idx):
return False
if any(s[1] != t[1] for s, t in zip(start_char_idx, target_char_idx)):
return False
for (start_idx, start_char), (target_idx, _) in zip(start_char_idx, target_char_idx):
if start_char == 'L' and start_idx < target_idx:
return False
elif start_char == 'R' and start_idx > target_idx:
return False
return True
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > String' 카테고리의 다른 글
(Python3) - LeetCode (Easy) : 2185. Counting Words With a Given Prefix (0) | 2025.01.09 |
---|---|
(Python3) - LeetCode (Medium) : 1930. Unique Length-3 Palindromic Subsequences (0) | 2025.01.04 |
(Python3) - 프로그래머스(코딩테스트 입문) : 잘라서 배열로 저장하기 (0) | 2024.11.03 |
(Python3) - 프로그래머스(코딩테스트 입문) : A로 B 만들기 (0) | 2024.10.31 |
(Python3) - 프로그래머스(코딩테스트 입문) : OX퀴즈 (0) | 2024.10.31 |