python - 在一个字符串中查找 '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')
我的代码打印了很多“是”!
解决方案
匹配字符串的问题通常最好通过正则表达式来解决。
将算法(例如评估、计算、匹配、创建数据结构等)与副作用(例如打印)分开也是一种很好的做法,因为这样可以进行单元测试。
下面的代码应该可以解决您的问题:
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
推荐阅读
- java - Car 对象和 Dog 对象是否用于现实生活中的程序?
- xamarin - 通过 TabBar Xaml 将视图模型中的参数传递给页面的 ctor?
- flask - 如何正确更新具有新值的外键?
- javascript - 在前端从 nodejs 管理 jwt
- javascript - js如何计算上传速度
- java - 实现验证方法以仅允许在 Java 中输入字符串
- django - 我无法访问新保存的模型实例的 ID 以用于处理同一页面中的另一个表单
- sql - Sql 更新表与其他表的连接总和
- java - 在 java 中格式化小时 20h 10m 5000s 到 20h 10m 10s
- c# - 在 unitTest [.net] 中使用 Webhost 和 Webhook 接收器