Python程序查找包含唯一字符的字符串总数
假设我们有一个包含小写字母的字符串 s,我们需要找到包含唯一字符的所有子字符串的总数。
因此,如果输入类似于“xxyy”,则输出将为 6,因为子字符串为 [x, x, xx, y, y, yy]
为了解决这个问题,我们将遵循以下步骤:
- total := 0
- previous := 空字符串
- 对于字符串 s 中的每个字符 c,执行以下操作:
- 如果 c 与 previous 不相同,则:
- previous := c
- temp := 1
- 否则:
- temp := temp + 1
- total := total + temp
- 如果 c 与 previous 不相同,则:
- 返回 total
让我们看看以下实现,以便更好地理解:
示例
class Solution:
def solve(self, s):
total = 0
previous = ''
for c in s:
if c != previous:
previous = c
in_a_row = 1
else:
in_a_row += 1
total += in_a_row
return total
ob = Solution()
print(ob.solve("xxyy"))输入
"xxyy"
输出
6
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP