题目不是很难,开始没看清,错了好几次。。。
判断出现最多的字母和最少的,我的方法是先把单词重新排序,这样相同的字母就会在一块,然后判断最大连续段和最小连续段
题:http://acm.nyist.net/JudgeOnline/problem.php?pid=62
#include<iostream>
#include<algorithm>
#include<math.h>
#include<string.h>
using namespace std;
bool justifyprime(int n) //判断素数
{ if(n<=0)
return false;
if(n==1)
return false;
else if(n==2||n==3)
return true;
else
{
for(int i=2;i<=sqrt(n);i++)
{
if(n%i==0)
return false;
}
return true;
}
}
bool compare(char s1,char s2)
{
return s1<s2?true:false;
}
int main()
{
int N;
cin>>N;
while(N--)
{
char str[101];
int len;
cin>>str;
len=strlen(str);
sort(str,str+len,compare); 单词按照字母表顺序递增排序
int MAX=1,temp=1,Min=100;
for(int i=1;i<=len;i++)
{
if(str[i]==str[i-1])
{
temp++;
if(temp>MAX)
MAX=temp; //相同则temp++;temp比较max值,不断更新max使得得到最大值
}
else
{ if(temp<Min) 后一个和前一个不同 先将前一段的长度和min比较,更新min值,再把temp设定为1,重新开始计数
Min=temp;
temp=1;
}
}
if(justifyprime(MAX-Min)==true)
{
cout<<"Lucky Word"<<endl;
cout<<MAX-Min<<endl;
}
else
{
cout<<"No Answer"<<endl;
cout<<0<<endl;
}
}
}
例程是用当做整形的思想来做的:很巧妙啊
#include<iostream>
#include<string>
#include<algorithm>
#include<numeric>
using namespace std;
bool isPrime(int n)
{
if(n==0) return false;
if(n==1) return false;
if(n==2) return true;
for(int i=2;i*i<=n;i++)
{
if(n%i==0) return false;
}
return true;
}
int main()
{
int n;
string str;
cin>>n;
while(n--)
{
int count[26]={0};
cin>>str;
for(int i=0;i!=str.size();++i)
{
++count[str[i]-'a'];
}
int nn=*max_element(count,count+26)-*min_element(count,count+26);
if(isPrime(nn)) cout<<"Lucky Word"<<endl<<nn<<endl;
else cout<<"No Answer"<<endl<<0<<endl;
}
}