มี String s, t ประกอบ 'A', 'B', '#' ต้องเช็คว่า s -> t ได้โดย: A เดินซ้ายได้, B เดินขวาได้, A,B ไม่ข้ามกัน
เช่น Input s = "##AB##B", t = "A###B#B" Output True (A เดินซ้ายสุด, B กลางเดินขวา 1 Step)
ขั้นตอนแก้:
- เช็ค Length และ Count ของ A, B เท่ากัน
- Match A และ B ใน s กับ t ตามลำดับ: A ใน s ต้องอยู่ขวา/เท่ากับ A ใน t (เดินซ้าย), B ใน s ต้องอยู่ซ้าย/เท่ากับ B ใน t (เดินขวา)
ตัวอย่างโค้ด
def solve(s, t):
s = list(s)
t = list(t)
if len(s) != len(t):
return False
if s.count('A') != t.count('A') or s.count('B') != t.count('B'):
return False
for i in range(len(s)):
if s[i] != '#':
for j in range(len(t)):
if (t[j] != s[i]) and t[j] != '#':
return False
if t[j] == s[i]:
t[j] = '#'
if s[i] == 'A' and i < j:
return False
if s[i] == 'B' and i > j:
return False
break
return True
s = "##AB##B"
t = "A###B#B"
print(solve(s, t))
Input
"##AB##B", "A###B#B"
Output
True