返回介绍

solution / 2000-2099 / 2063.Vowels of All Substrings / README_EN

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

2063. Vowels of All Substrings

中文文档

Description

Given a string word, return _the sum of the number of vowels (_'a', 'e'_,_ 'i'_,_ 'o'_, and_ 'u'_)_ _in every substring of _word.

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

Note: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calculations.

 

Example 1:

Input: word = "aba"
Output: 6
Explanation: 
All possible substrings are: "a", "ab", "aba", "b", "ba", and "a".
- "b" has 0 vowels in it
- "a", "ab", "ba", and "a" have 1 vowel each
- "aba" has 2 vowels in it
Hence, the total sum of vowels = 0 + 1 + 1 + 1 + 1 + 2 = 6. 

Example 2:

Input: word = "abc"
Output: 3
Explanation: 
All possible substrings are: "a", "ab", "abc", "b", "bc", and "c".
- "a", "ab", and "abc" have 1 vowel each
- "b", "bc", and "c" have 0 vowels each
Hence, the total sum of vowels = 1 + 1 + 1 + 0 + 0 + 0 = 3.

Example 3:

Input: word = "ltcd"
Output: 0
Explanation: There are no vowels in any substring of "ltcd".

 

Constraints:

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

Solutions

Solution 1

class Solution:
  def countVowels(self, word: str) -> int:
    n = len(word)
    return sum((i + 1) * (n - i) for i, c in enumerate(word) if c in 'aeiou')
class Solution {
  public long countVowels(String word) {
    long ans = 0;
    for (int i = 0, n = word.length(); i < n; ++i) {
      char c = word.charAt(i);
      if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
        ans += (i + 1L) * (n - i);
      }
    }
    return ans;
  }
}
class Solution {
public:
  long long countVowels(string word) {
    long long ans = 0;
    for (int i = 0, n = word.size(); i < n; ++i) {
      char c = word[i];
      if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
        ans += (i + 1LL) * (n - i);
      }
    }
    return ans;
  }
};
func countVowels(word string) (ans int64) {
  for i, c := range word {
    if c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' {
      ans += int64((i + 1) * (len(word) - i))
    }
  }
  return
}
function countVowels(word: string): number {
  const n = word.length;
  let ans = 0;
  for (let i = 0; i < n; ++i) {
    if (['a', 'e', 'i', 'o', 'u'].includes(word[i])) {
      ans += (i + 1) * (n - i);
    }
  }
  return ans;
}

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

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

发布评论

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