首页 > 解决方案 > 在一个字符串中查找 'BA' 和 'AB' 而不重叠

问题描述

我在 stackoverflow 和其他网站中搜索我的答案,但我找不到我的答案。 我不想使用库,我想要更简单的答案

它必须这样做: 得到 'ABBA' 和 print('YES') / 得到 'BAAB' 和 print('YES') / 得到 'ABA' 和 print('NO') / 得到 'ABHA' 和 print('NO ')

我写了这段代码:

str = input().upper()
a = str.find('AB')
b = str.find('BA')


if ('AB' in str ) == True:
    a = a+2 and 'BA' in str[a:] == True
    print('YES')

if ('BA' in str ) == True:
    b = b+2 and 'AB' in str[b:] == True
    print('YES')

if ('AB' in str[b:]) == False:
    print('NO')
elif ('BA' in str[a:]) == False:
    print('NO')

我的代码打印了很多“是”!

标签: pythonfindsequence

解决方案


匹配字符串的问题通常最好通过正则表达式来解决。

将算法(例如评估、计算、匹配、创建数据结构等)与副作用(例如打印)分开也是一种很好的做法,因为这样可以进行单元测试。

下面的代码应该可以解决您的问题:

import re
regex = re.compile(r'^.*(AB.*BA|BA.*AB).*$')

def isABBA(s):
    return regex.match(s) is not None

assert isABBA('ABBA')
assert isABBA('BAAB')
assert not isABBA('ABA')
assert not isABBA('ABHA')

for i in ['ABBA','BAAB','ABA','ABHA']:
    print('YES' if isABBA(i) else 'NO')

# Output:
# YES
# YES
# NO
# NO

推荐阅读