子子符串的个数

版权声明:非商业性使用,禁止演绎,转载请保留原文链接及作者 https://blog.csdn.net/qq_39478237/article/details/89320140

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

题目描述

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

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

解决方案

#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;
}

猜你喜欢

转载自blog.csdn.net/qq_39478237/article/details/89320140
今日推荐