网易游戏雷火盘古2017实习生招聘笔试题(字符串编码)
题意:
给定一个字符串,请你将字符串重新编码,将连续的字符替换成“连续出现的个数+字符”。比如字符串AAAABCCDAA会被编码成4A1B2C1D2A。
输入描述:
每个测试输入包含1个测试用例
每个测试用例输入只有一行字符串,字符串只包括大写英文字母,长度不超过10000。
输出描述:
输出编码后的字符串
输入例子:
AAAABCCDAA
输出例子:
4A1B2C1D2A
分析:
直接暴力遍历一遍,存到一个新的字符串中。
Code:
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<set>
#include<map>
#include<vector>
#include<string>
#include<string.h>
using namespace std;
typedef long long LL;
const int MAXN = 1005;
string int2str(int k){
string s = "";
while(k){
s += '0' + k%10;
k /= 10;
}
reverse(s.begin(),s.end());
return s;
}
int main()
{
string s;
while(cin>>s){
string res="";
int k = 1;
for(int i=1;i<s.size();i++){
if(s[i] == s[i-1]) k++;
else{
res += int2str(k);
res += s[i-1];
k = 1;
}
}
res += int2str(k);
res += s[s.size()-1];
cout<<res<<endl;
}
return 0;
}