题目描述
LZY又来写程序模拟随机字符串了,你们是不是很想揍他?先别急,先AC这题再揍。LZY今天又模拟了一串随机字符串,他想让你们帮帮他,把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。输出每一个字符串片段的长度。
输入
测试数据由多组测试样例组成。每组测试样例第一行输入一个字符串 s ( 1 <= s.length <= 1000000),字符串中只存在 小写字母 a —— z
输出
输出分离后每个字符串片段的长度
样例输入 Copy
ababcbacadefegdehijhklij
样例输出 Copy
9 7 8
提示
第一组样例解释:
划分结果为 “ababcbaca”, “defegde”, “hijhklij”。
每个字母最多出现在一个片段中。
像 “ababcbacadefegde”, “hijhklij” 的划分是错误的,因为划分的片段数较少。
- 先给大家看一下我写的第一版
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
while( cin >> s ){
/* 分离LZY的字符串 */
int len = s.size();
int i = 0, k = 0;
int temp =0;
while (i < len){
for( i; i <= k; i ++){
for(int j = len - 1; j > k; j--){
if(s[i] == s[j]){
k = j;
break;
}
}
}
if(temp != 0)cout<< " ";
cout << i - temp ;
temp = i;
k ++;
i = k;
}
cout<< endl;
}
return 0;
}
- emmm,2秒,超时了
- 然后问了唐学长,可以先用桶排序把最后一个字母出现的位置记录下来
- 然后这些那样,,,用脚就可以写出来了
- 这个方法是0.2秒,快了十倍
- 可能唐学长用了ios::sync_with_stdio(false);
- 可以加快速度,我也不太懂,可我又不敢删
#include <bits/stdc++.h>
using namespace std;
int a[150];
int main()
{
ios::sync_with_stdio(false);
string s;
while( cin >> s ){
/* 分离LZY的字符串 */
memset(a,0,sizeof(a));
int len = s.size();
for(int i = 0; i < len; i ++){
a [s[i]] = i;
}
int temp = 0, k = 0, i = 0;
while(i < len){
for( i = i; i <= k; i ++){
if( k < a[s[i]] )k = a[s[i]];
}
if(temp != 0) cout << " ";
cout << i - temp ;
k++;//这个是重点,给下一次循环用的
temp = i;
}
cout << endl ;
}
return 0;
}