LeetCode 题解工作台
统计以给定字符开头和结尾的子字符串总数
给你一个字符串 s 和一个字符 c 。返回在字符串 s 中并且以 c 字符开头和结尾的 非空子字符串 的总数。 示例 1: 输入: s = "abada", c = "a" 输出: 6 解释: 以 "a" 开头和结尾的子字符串有: " a bada" 、 " aba da" 、 " abada " …
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数学·string
答案摘要
我们可以先统计字符串 中字符 的个数,记为 。 每个 字符可以单独作为一个子字符串,所以有 个子字符串满足条件。每个 字符可以和其他 字符组成一个满足条件的子字符串,所以有 $\frac{cnt \times (cnt - 1)}{2}$ 个子字符串满足条件。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路
题目描述
给你一个字符串 s 和一个字符 c 。返回在字符串 s 中并且以 c 字符开头和结尾的非空子字符串的总数。
示例 1:
输入:s = "abada", c = "a"
输出:6
解释:以 "a" 开头和结尾的子字符串有: "abada"、"abada"、"abada"、"abada"、"abada"、"abada"。
示例 2:
输入:s = "zzz", c = "z"
输出:6
解释:字符串 s 中总共有 6 个子字符串,并且它们都以 "z" 开头和结尾。
提示:
1 <= s.length <= 105s和c均由小写英文字母组成。
解题思路
方法一:数学
我们可以先统计字符串 中字符 的个数,记为 。
每个 字符可以单独作为一个子字符串,所以有 个子字符串满足条件。每个 字符可以和其他 字符组成一个满足条件的子字符串,所以有 个子字符串满足条件。
所以答案为 。
时间复杂度 ,其中 为字符串 的长度。空间复杂度 。
class Solution:
def countSubstrings(self, s: str, c: str) -> int:
cnt = s.count(c)
return cnt + cnt * (cnt - 1) // 2
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Check if the candidate counts occurrences correctly and applies the mathematical formula properly.
- question_mark
Look for efficient handling of large strings, as the length can reach 10^5.
- question_mark
Assess if the candidate recognizes the need to avoid brute force approaches like checking all possible substrings.
常见陷阱
外企场景- error
Forgetting to include substrings of length 1 in the calculation.
- error
Confusing the mathematical formula for substring counting, especially how to handle the pairings of occurrences.
- error
Overcomplicating the problem by trying to find substrings directly, instead of focusing on character occurrences.
进阶变体
外企场景- arrow_right_alt
Modify the problem to allow multiple characters instead of just one to be checked at the beginning and end.
- arrow_right_alt
Extend the problem to handle strings with upper and lowercase characters or other special characters.
- arrow_right_alt
Change the task to count substrings that start with `c` and end with a different character.