[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
在庆祝祖国母亲70华诞之际,老师给小乐乐出了一个问题。大家都知道China的英文缩写是CHN,那么给你一个字符串s,你需要做的是统计s中子串“CHN”的个数。
子串的定义:存在任意下标a < b <
c,那么“s[a]s[b]s[c]”就构成s的一个子串。如“ABC”的子串有“A”、“B”、“C”、“AB”、“AC”、“BC”、“ABC”。
输入描述:
输入只包含大写字母的字符串s。(1 ≤ length ≤ 8000)
输出描述:
输出一个整数,为字符串s中字串“CHN”的数量。
示例1
输入:
CCHNCHN
输出:
7
第一种方法算法复杂度高,遍历全部的可能性;
int main() { char arr[8001] = { 0 }; scanf("%s", arr); int st = 0; int u = 0;
while (arr[u] != 0) { st++; u++; } st = st +1; int i = 0; int j = 0; int k = 0;
int count = 0; for (i = 0; i < st - 1; i++) { if (arr[i] == 'C') { for (j = i +
1; j < st - 1; j++) { if (arr[j] == 'H') { for (k = j + 1; k < st - 1; k++) { if
(arr[k] == 'N') { count++; } } } } } } printf("%d", count); return 0; }
方法二
可以先找C的子序列,那么遇到H的话就组成CH此时有C个"CH”序列
也就是说ch的个数取决于c的个数,同理,当你找到“N”的时候,就是“CH“还有"N组成的“CHN”,"CH“的个数就是“CHN”的个数,把个数做累加。
#include<stdio.h> #include<string.h> int main() { char str[8000]; scanf("%s\n",
str);//CCHNCHN char* ps = str; long long c = 0, ch = 0, chn = 0; while (*ps) {
if (*ps == 'C') { c++; } else if (*ps == 'H') { ch += c; } else if (*ps == 'N')
{ chn += ch; } ps++; } printf("%lld\n", chn); return 0; }