Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python에서 주어진 문자열을 연결한 후 주어진 문자열을 생성할 수 있는지 확인

<시간/>

두 개의 문자열 s와 t, r이 있다고 가정하고 r =s | t 또는 r =t + s 여기서 | 연결을 나타냅니다.

따라서 입력이 s ="world" t ="hello" r ="helloworld"와 같으면 출력은 "helloworld" (r) ="hello" (t) | "세계"(들).

이 문제를 해결하기 위해 다음 단계를 따릅니다. −

  • r의 크기가 s와 t의 길이의 합과 같지 않으면
    • 거짓을 반환
  • r이 s로 시작하면
    • r이 t로 끝나면
      • 참 반환
  • r이 t로 시작하면
    • r이 s로 끝나면
      • 참 반환
  • 거짓을 반환

이해를 돕기 위해 다음 구현을 살펴보겠습니다. −

예시 코드

def solve(s, t, r):
   if len(r) != len(s) + len(t):
      return False

   if r.startswith(s):
      if r.endswith(t):
         return True
         
   if r.startswith(t):
      if r.endswith(s):
         return True
     
   return False  

s = "world"
t = "hello"
r = "helloworld"
print(solve(s, t, r))

입력

"world", "hello", "helloworld"

출력

True