腾讯校招字符串笔试题

一个由小写字母组成的字符串可以看成一些同一字母的最大碎片组成的。例如,"aaabbaaac"是由下面碎片组成的:'aaa','bb','c'。牛牛现在给定一个字符串,请你帮助计算这个字符串的所有碎片的平均长度是多少。

输入描述:

输入包括一个字符串s,字符串s的长度length(1 ≤ length ≤ 50),s只含小写字母('a'-'z')

输出描述:

输出一个整数,表示所有碎片的平均长度,四舍五入保留两位小数。

如样例所示: s = "aaabbaaac"
所有碎片的平均长度 = (3 + 2 + 3 + 1) / 4 = 2.25

输入例子1:

aaabbaaac

输出例子1:

2.25

首先按照题目要求把字符串拆分到vector中,然后统计即可

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
	string str;
	vector<string> res;
	cin >> str;
	int n = str.size();
	int i = 0;
	while (i < n) {
		string tempstr = "";
		char tempc = str[i];
		while(str[i] == tempc) {
			tempstr += str[i];
			i++;
		}
		//cout << tempstr << endl;
		res.push_back(tempstr);
	}
	int count = 0;
	for (auto v : res) {
		count += v.size();
		//cout << v << endl;
	}
	printf("%.2f", 1.0*count / res.size());
}

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/89442418