假设我们有两个字符串s和t,其中只有三个字符“ A”,“ B”和“#”。我们必须检查是否可以通过对s执行这些操作来将s转换为t。
“ A”只能移到左侧
“ B”只能移到右侧
'A'和'B'都不能互相交叉
因此,如果输入类似于s =“ ## AB ## B” t =“ A ### B#B”,则输出将为True,因为s A可以轻松移至最左侧,中间B可以向右移动一步
让我们看下面的实现以更好地理解-
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))"##AB##B", "A###B#B"输出结果
True