[Leetcode] Rotate String

LOSSS·2021년 2월 17일
0

면접에서 나온 질문

We are given two strings, A and B.

A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A.

두 개의 문자열 A 와 B 가 주어졌다.

A 를 이동하는 것은 문자열 A 를 가지고 가장 왼쪽 문자값을 가장 오른쪽 문자값으로 옮기는 것으로 구성된다. 예를 들어 A 가 'abcde' 이면, 한 번의 이동으로 그것은 'bcdea' 가 될 것이다. A 가 몇 번의 이동 끝에 B 가 될 수 있다면 True 를 반환해라.

  1. 하나씩 만들어가면서 비교
class Solution:
    def rotateString(self, A: str, B: str) -> bool:
        if len(A) != len(B):
            return False
        
        if len(A) == 0 and len(B) == 0:
            return True
        
        i = 1
        C = A
        
        while i < len(A):
            C = C[1:] + C[0]
            if C == B:
                return True
            i += 1
            
        return False
  1. A 를 두 번 더한 것에는 무조건 B가 있다. 단, 두 개의 문자열의 길이는 같아야 한다.
var rotateString = function(A, B) {
    let C = A + A
    return A.length === B.length && C.includes(B)
};




Solution 에 내 머리로는 전혀 생각해낼 수 없는 두 가지 방법이 더 있는데
궁금하다면 아래 링크로 ⬇⬇⬇

[Leetcode] Rotate String

0개의 댓글