问题描述
小红在玩一个字符串游戏,她发现当字符串中出现 "chhc" 这样的特殊子串时,这个子串会有一个权值。具体来说,对于字符串中的任意子串,如果该子串等于 "chhc",那么它的权值定义为子串中所有字符的ASCII码之和。现在小红有一个很长的字符串,她想知道所有 "chhc" 子串的权值总和是多少。
要求:
- 设计一个算法,在给定的字符串中找出所有连续子串等于 "chhc" 的起始位置,并计算这些子串的权值总和。
- 注意算法的时间复杂度应尽可能低,以处理大规模字符串输入。
测试样例
样例1:
输入:
s = "chhcxychhc"输出:812解释:字符串中有两个 "chhc" 子串,第一个从索引0开始(字符'c','h','h','c'),第二个从索引6开始(字符'c','h','h','c')。每个 "chhc" 的ASCII码和为:99 + 104 + 104 + 99 = 406。总权值为406 × 2 = 812。
样例2:
输入:
s = "chhchhc"输出:812解释:字符串中有两个 "chhc" 子串,第一个从索引0开始(字符'c','h','h','c'),第二个从索引3开始(字符'c','h','h','c')。每个子串的ASCII码和为406,总权值为406 × 2 = 812。
样例3:
输入:
s = "abcchhcd"输出:406解释:字符串中有一个 "chhc" 子串从索引3开始(字符'c','h','h','c'),ASCII码和为99 + 104 + 104 + 99 = 406。
约束条件
- 1 ≤ s.length ≤ 10^5
- 字符串 s 仅由小写英文字母组成
- "chhc" 子串可能出现多次,且可能重叠(例如 "chhchhc" 中索引0-3和3-6是两个重叠的子串)
- 需要计算所有出现位置的权值总和
程序代码
#include <stdio.h>
#include <string.h>
int totalWeight(char* s) {
int n = strlen(s);
int total = 0;
// "chhc" 的 ASCII 码之和
int weight = 'c' + 'h' + 'h' + 'c'; // 99 + 104 + 104 + 99 = 406
for (int i = 0; i + 3 < n; i++) {
if (s[i] == 'c' && s[i+1] == 'h' && s[i+2] == 'h' && s[i+3] == 'c') {
total += weight;
}
}
return total;
}
int main() {
printf("%d\n", totalWeight("chhcxychhc")); // 812
printf("%d\n", totalWeight("chhchhc")); // 812
printf("%d\n", totalWeight("abcchhcd")); // 406
return 0;
}
#include <stdio.h> #include <string.h> int totalWeight(char* s) { int n = strlen(s); int total = 0; // "chhc" 的 ASCII 码之和 int weight = 'c' + 'h' + 'h' + 'c'; // 99 + 104 + 104 + 99 = 406 for (int i = 0; i + 3 < n; i++) { if (s[i] == 'c' && s[i+1] == 'h' && s[i+2] == 'h' && s[i+3] == 'c') { total += weight; } } return total; } int main() { printf("%d\n", totalWeight("chhcxychhc")); // 812 printf("%d\n", totalWeight("chhchhc")); // 812 printf("%d\n", totalWeight("abcchhcd")); // 406 return 0; }