Fork me on GitHub

字符串区间的个数

这个题是一道CVTE在线笔试题,题目是我回忆写的,答案是我自己的思路,如果哪位大神有更好的解决方案,希望可以留言或者私我交流。如有不明白请留言提出。

题目描述

给一个数字字符串,长度为L,并给定一个K,请在字符串中找出区间大小为K,排序后的字符串是连续(相同为连续)的个数。输出这样的字符串的个数。

示例:
123456789  K=2
8  12,23,34,45,56,67,78,89
1345321898 K=3
4 345,453,321,898

解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<iostream>
#include<algorithm>
using namespace std;
int func(std::string& str, int L, int k)
{
std::string ret;
int count = 0;
for (int i = 0; i < L - k; i++)
{
ret = str.substr(i, k);
std::sort(ret.begin(), ret.end());
//判断该区间是否连续
int n = 0;
for (int j = 0; j < k - 1; j++)
{
if (ret[j+1] - ret[j] == 1) {
n += 1;
}
else {
break;
}
}
//当n = k-1时,说明上面的差判断了k-1次,就说明该串是连续的
if (n == k - 1) {
count += 1;
}
}
return count+1;
}

int main()
{
int num = 0;
// string str = "123456789"; //K=2; 8
string str = "1345321898"; //K=3; 4
int L = 10, K = 3;
cout << func(str,L,K) << endl;

return 0;
}

本文标题:字符串区间的个数

文章作者:LiuXiaoKun

发布时间:2019年04月15日 - 20:04

最后更新:2019年04月15日 - 20:04

原始链接:https://LiuZiQiao.github.io/2019/04/15/字符串区间的个数/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%