1759. 统计同质子字符串的数目
https://leetcode.cn/problems/count-number-of-homogenous-substrings/description/
1. 暴力解法:
class Solution:
def countHomogenous(self, s: str) -> int:
n = 0
for i in range(len(s)):
for j in range(i, len(s)):
sub_s = s[i:j]
if j == i:
n += 1
elif s[j] == s[i]:
n += 1
else:
break
return n % (10 ** 9 + 7)
时间复杂度:
2. 双指针解法
核心思想是,计算以j为结尾,开头在i以后的同质字符串数目
class Solution:
def countHomogenous(self, s: str) -> int:
n = 0
i = 0
j = 0
is_str = True
while i < len(s) and j < len(s):
if i == j: # 字母本身
n += 1
j += 1
elif s[j] == s[j - 1]: # 连续字符串
temp_len = j - i + 1
n += temp_len
j += 1
else:
i = j
return n % (10 ** 9 + 7)
时间复杂度
3. 官方优雅解法
class Solution:
def countHomogenous(self, s: str) -> int:
n = 0
for k, sub_s in groupby(s):
sub_s = list(sub_s)
temp_len = len(sub_s)
n += (temp_len + 1) * temp_len // 2
return n % (10 ** 9 + 7)
时间复杂度