用 Python 编写程序,查找包含一个唯一字符的字符串总数

pythonserver side programmingprogramming更新于 2026/1/11 6:36:17

假设我们有一个由小写字母组成的字符串 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
  • 返回 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

相关文章


有用资源