Input: s ="abbca"Output: 28Explanation: 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 is5.- Substrings of length 2:"ab","bb","bc","ca" have an appeal of 2,1,2, and 2 respectively. The sum is7.- Substrings of length 3:"abb","bbc","bca" have an appeal of 2,2, and 3 respectively. The sum is7.- Substrings of length 4:"abbc","bbca" have an appeal of 3 and 3 respectively. The sum is6.- Substrings of length 5:"abbca" has an appeal of 3. The sum is3.The total sum is5+7+7+6+3=28.
Input: s ="code"Output: 20Explanation: 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 is4.- Substrings of length 2:"co","od","de" have an appeal of 2,2, and 2 respectively. The sum is6.- Substrings of length 3:"cod","ode" have an appeal of 3 and 3 respectively. The sum is6.- Substrings of length 4:"code" has an appeal of 4. The sum is4.The total sum is4+6+6+4=20.
Track the last seen index for each character. For each position, the number of substrings where s[i] is the rightmost occurrence is (i - last[c]), and each such substring contributes to the total appeal.
#include<vector>#include<string>usingnamespace std;
classSolution {
public:longlong appealSum(string s) {
vector<int> last(26, -1);
longlong res =0, cur =0;
for (int i =0; i < s.size(); ++i) {
cur += i - last[s[i] -'a'];
last[s[i] -'a'] = i;
res += cur;
}
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
publiclongappealSum(String s) {
int[] last =newint[26];
for (int i = 0; i < 26; ++i) last[i]=-1;
long res = 0, cur = 0;
for (int i = 0; i < s.length(); ++i) {
cur += i - last[s.charAt(i) -'a'];
last[s.charAt(i) -'a']= i;
res += cur;
}
return res;
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defappealSum(self, s: str) -> int:
last = [-1] *26 res = cur =0for i, c in enumerate(s):
cur += i - last[ord(c) - ord('a')]
last[ord(c) - ord('a')] = i
res += cur
return res
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnappeal_sum(s: String) -> i64 {
letmut last = [-1; 26];
letmut res =0i64;
letmut cur =0i64;
for (i, b) in s.bytes().enumerate() {
let idx = (b -b'a') asusize;
cur += (i asi64- last[idx]);
last[idx] = i asi64;
res += cur;
}
res
}
}