Cho ba chuỗi s, t, r. Kiểm tra xem r có bằng s + t hoặc t + s hay không.
Ví dụ: s = "world", t = "hello", r = "helloworld" → True vì r = t + s.
Giải thuật
- Nếu độ dài
rkhác tổng độ dàisvàt→False. - Kiểm tra
rcó bắt đầu bằngsvà kết thúc bằngt. - Hoặc
rbắt đầu bằngtvà kết thúc bằngs.
Mã ví dụ
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))
Đầu vào
"world", "hello", "helloworld"
Đầu ra
True