小乐乐与字符串(新生赛)

小乐乐与字符串

题目描述

在庆祝祖国母亲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”的数量
题意:找“CHN”的子序列
 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 int main()
 5 {
 6     ios::sync_with_stdio(0);
 7     string s;
 8     cin >> s;
 9     long long ans = 0;
10     long long sum = 0;
11     int c=0, h=0;
12     int u;
13     for (int i = 0; i < s.size(); i++)
14     {
15         if (s[i] == 'C')
16         {
17             c++;
18         }
19         else if (s[i] == 'H')
20         {
21             h += c;
22         }
23         else if(s[i]=='N')
24         {
25             ans +=h;
26         }
27     }
28     cout << ans << endl;
29     return 0;
30 }
 

猜你喜欢

转载自www.cnblogs.com/thief-of-book/p/11825842.html