返回介绍

solution / 2000-2099 / 2083.Substrings That Begin and End With the Same Letter / README_EN

发布于 2024-06-17 01:03:11 字数 3389 浏览 0 评论 0 收藏 0

2083. Substrings That Begin and End With the Same Letter

中文文档

Description

You are given a 0-indexed string s consisting of only lowercase English letters. Return _the number of substrings in _s _that begin and end with the same character._

A substring is a contiguous non-empty sequence of characters within a string.

 

Example 1:

Input: s = "abcba"
Output: 7
Explanation:
The substrings of length 1 that start and end with the same letter are: "a", "b", "c", "b", and "a".
The substring of length 3 that starts and ends with the same letter is: "bcb".
The substring of length 5 that starts and ends with the same letter is: "abcba".

Example 2:

Input: s = "abacad"
Output: 9
Explanation:
The substrings of length 1 that start and end with the same letter are: "a", "b", "a", "c", "a", and "d".
The substrings of length 3 that start and end with the same letter are: "aba" and "aca".
The substring of length 5 that starts and ends with the same letter is: "abaca".

Example 3:

Input: s = "a"
Output: 1
Explanation:
The substring of length 1 that starts and ends with the same letter is: "a".

 

Constraints:

  • 1 <= s.length <= 105
  • s consists only of lowercase English letters.

Solutions

Solution 1

class Solution:
  def numberOfSubstrings(self, s: str) -> int:
    cnt = Counter()
    ans = 0
    for c in s:
      cnt[c] += 1
      ans += cnt[c]
    return ans
class Solution {
  public long numberOfSubstrings(String s) {
    int[] cnt = new int[26];
    long ans = 0;
    for (int i = 0; i < s.length(); ++i) {
      int j = s.charAt(i) - 'a';
      ++cnt[j];
      ans += cnt[j];
    }
    return ans;
  }
}
class Solution {
public:
  long long numberOfSubstrings(string s) {
    int cnt[26]{};
    long long ans = 0;
    for (char& c : s) {
      ans += ++cnt[c - 'a'];
    }
    return ans;
  }
};
func numberOfSubstrings(s string) (ans int64) {
  cnt := [26]int{}
  for _, c := range s {
    c -= 'a'
    cnt[c]++
    ans += int64(cnt[c])
  }
  return ans
}

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

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

发布评论

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