假设我们有一个小写字母的字符串s,我们必须找到包含一个唯一字符的子字符串的总数。
因此,如果输入类似于“ xxyy”,则输出将为6,因为子字符串为[x,x,xx,y,y,yy]
为了解决这个问题,我们将遵循以下步骤-
总计:= 0
上一个:=空字符串
对于s中的每个字符c,
温度:=温度+ 1
上一个:= c
温度:= 1
如果c与先前不同,则
除此以外,
合计:=合计+温度
总回报
让我们看下面的实现以更好地理解-
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