ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Count Subarray by Element

2022-06-27 07:32:09  阅读:160  来源: 互联网

标签:Count int respectively sum Substrings Element length Subarray appeal


2262. Total Appeal of A String Hard

The appeal of a string is the number of distinct characters found in the string.

  • For example, the appeal of "abbca" is 3 because it has 3 distinct characters: 'a''b', and 'c'.

Given a string s, return the total appeal of all of its substrings.

A substring is a contiguous sequence of characters within a string.

 Example 1:

Input: s = "abbca"
Output: 28
Explanation: The following are the substrings of "abbca":
- Substrings of length 1: "a", "b", "b", "c", "a" have an appeal of 1, 1, 1, 1, and 1 respectively. The sum is 5.
- Substrings of length 2: "ab", "bb", "bc", "ca" have an appeal of 2, 1, 2, and 2 respectively. The sum is 7.
- Substrings of length 3: "abb", "bbc", "bca" have an appeal of 2, 2, and 3 respectively. The sum is 7.
- Substrings of length 4: "abbc", "bbca" have an appeal of 3 and 3 respectively. The sum is 6.
- Substrings of length 5: "abbca" has an appeal of 3. The sum is 3.
The total sum is 5 + 7 + 7 + 6 + 3 = 28.

Example 2:

Input: s = "code"
Output: 20
Explanation: The following are the substrings of "code":
- Substrings of length 1: "c", "o", "d", "e" have an appeal of 1, 1, 1, and 1 respectively. The sum is 4.
- Substrings of length 2: "co", "od", "de" have an appeal of 2, 2, and 2 respectively. The sum is 6.
- Substrings of length 3: "cod", "ode" have an appeal of 3 and 3 respectively. The sum is 6.
- Substrings of length 4: "code" has an appeal of 4. The sum is 4.
The total sum is 4 + 6 + 6 + 4 = 20.

 Constraints:

  • 1 <= s.length <= 105
  • s consists of lowercase English letters.
left表示能为左侧作出贡献的个数
right 表示能为右侧作出贡献的个数
5      01234
-1     abbca
left:  12144
right: 54321

        5+8+3+8+4

 

class Solution {
    public long appealSum(String s) {
        int[] appearPos = new int[26];
        int len = s.length();
        Arrays.fill(appearPos, -1);
        long sum = 0;
        for(int i = 0; i < s.length(); i++){
            int left = i-appearPos[s.charAt(i)-'a'];
            appearPos[s.charAt(i)-'a'] = i;
            sum += left*(len-i);
        }
        return sum;
    }
}

 

标签:Count,int,respectively,sum,Substrings,Element,length,Subarray,appeal
来源: https://www.cnblogs.com/cynrjy/p/16414957.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有