代码的基本编写格式:
#include <iostream>
using namespace std;
int main()
{
printf("Hello World\n");
printf("%d\n",123); //在笔试中,输出结果如果没有特殊要求,一定要加换
printf("%f\n",123.1111);
printf("%.2f\n",123.1516);
int num=0;
float f=0.01;
string s="abcd";
//打印变量的值
printf("%d\n",num);
printf("%.2f\n",f);
printf("%s\n",s.c_str());
//输入
int n=0;
scanf("%d",&n);
printf("%d\n",n);
float f2=0;
scanf("%f",&f2);
printf("%f\n",f2);
//字符串输入输出
string s2;
cin>>s2;
cout<<s2;
return 0;
}
第一题:字符串碎片:一个由小写字母组成的字符串可以看成一些同一字母的最大碎片组成的。例如,"aaabbaaac"
是由下面碎片组成的:'aaa'
,'bb'
,'c'
。牛牛现在给定一个字符串,请你帮助计算这个字符串的所有碎片的平均长度是多少。
#include <iostream>
using namespace std;
int main()
{
string s;
cin>>s ;
//for 循环
int count =1; // 碎片个数
char pre=s[0];
for(int i=0;i<s.size(); i++){ //当前字符串与前一个不相等
if(pre!=s[i]){
pre=s[i];
count++;//开始一个新的碎片
}
}
printf("%.2f\n",1.0*s.size()/count);
return 0;
}
第二题:计算重复字符串的长度
请从字符串中找出至少重复一次的子字符串的最大长度
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin>> s;
int res=0; //最大字符串长度
for(int i=0;i<s.size(); i++){
for(int j=i+1;j<s.size(); j++){
int len =0; //当前重复字符串的长度
int now= i; //保存当前下标
int post=j; //保存当前下标
while(s[now]==s[post]){
++now;
++post;
++len;
}
res=max(len,res);
}
}
printf("%d\n",res);
return 0;
}