📅  最后修改于: 2023-12-03 15:12:01.622000             🧑  作者: Mango
本文将介绍如何计算一个字符串中具有不同首尾字符的子串的数量。以下为 Python 代码实现。
def count_substrings(s: str) -> int:
count = 0
for i in range(len(s)):
for j in range(i+1, len(s)):
if s[i] != s[j]:
count += 1
return count
该函数 count_substrings
接收一个字符串 s
作为参数,并返回子串数量。
函数中的两层循环遍历字符串 s
,枚举所有的子串,判断子串的首尾字符是否相同。若不相同,则计数器 count
加一。
最终,函数返回结果即为具有不同首尾字符的子串数量。
以下为调用 count_substrings
函数的示例。
s = "abca"
print(count_substrings(s)) # 3
在字符串 s
中,存在以下三个具有不同首尾字符的子串:
因此,函数返回值为 3。
本文介绍了如何计算一个字符串中具有不同首尾字符的子串的数量,提供了 Python 代码实现,并给出了示例。