其他分享
首页 > 其他分享> > LeetCode 2262. Total Appeal of A String

LeetCode 2262. Total Appeal of A String

作者:互联网

原题链接在这里:https://leetcode.com/problems/total-appeal-of-a-string/

题目:

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

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:

题解:

For current char, how many points could it contribute. 

Total is the total points of appeal ending at current char.

There are 2 cases:

1. This char has never been appeared before, then it contributes to all the substring ending at this char.

2. This char has been appeard before, then it contributes to all the substring starting form its last appearence poisiton + 1 to this char.

Time Complexity: O(n). n = s.length().

Space: O(1).

AC Java:

 1 class Solution {
 2     public long appealSum(String s) {
 3         int [] last = new int[26];
 4         long res = 0;
 5         int total = 0;
 6         for(int i = 0; i < s.length(); i++){
 7             char c = s.charAt(i);
 8             total += i + 1 - last[c - 'a'];
 9             last[c - 'a'] = i + 1;
10             res += total;
11         }
12         
13         return res;
14     }
15 }

 

标签:total,appeal,respectively,sum,Substrings,length,2262,Appeal,Total
来源: https://www.cnblogs.com/Dylan-Java-NYC/p/16516217.html