返回介绍

solution / 3000-3099 / 3084.Count Substrings Starting and Ending with Given Character / README_EN

发布于 2024-06-17 01:02:57 字数 4317 浏览 0 评论 0 收藏 0

3084. Count Substrings Starting and Ending with Given Character

中文文档

Description

You are given a string s and a character c. Return _the total number of substrings of _s_ that start and end with _c_._

 

Example 1:

Input: s = "abada", c = "a"

Output: 6

Explanation: Substrings starting and ending with "a" are: "abada", "abada", "abada", "abada", "abada", "abada".

Example 2:

Input: s = "zzz", c = "z"

Output: 6

Explanation: There are a total of 6 substrings in s and all start and end with "z".

 

Constraints:

  • 1 <= s.length <= 105
  • s and c consist only of lowercase English letters.

Solutions

Solution 1: Mathematics

First, we can count the number of character $c$ in string $s$, denoted as $cnt$.

Each character $c$ can form a substring on its own, so there are $cnt$ substrings that meet the condition. Each character $c$ can form a substring with other $c$ characters, so there are $\frac{cnt \times (cnt - 1)}{2}$ substrings that meet the condition.

Therefore, the answer is $cnt + \frac{cnt \times (cnt - 1)}{2}$.

The time complexity is $O(n)$, where $n$ is the length of the string $s$. The space complexity is $O(1)$.

class Solution:
  def countSubstrings(self, s: str, c: str) -> int:
    cnt = s.count(c)
    return cnt + cnt * (cnt - 1) // 2
class Solution {
  public long countSubstrings(String s, char c) {
    long cnt = s.chars().filter(ch -> ch == c).count();
    return cnt + cnt * (cnt - 1) / 2;
  }
}
class Solution {
public:
  long long countSubstrings(string s, char c) {
    long long cnt = ranges::count(s, c);
    return cnt + cnt * (cnt - 1) / 2;
  }
};
func countSubstrings(s string, c byte) int64 {
  cnt := int64(strings.Count(s, string(c)))
  return cnt + cnt*(cnt-1)/2
}
function countSubstrings(s: string, c: string): number {
  const cnt = s.split('').filter(ch => ch === c).length;
  return cnt + Math.floor((cnt * (cnt - 1)) / 2);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文