求满足条件的最长子串的长度

题目描述:
给定一个字符串,只包含字母和数字,按要求找出字符串中的最长(连续)子的长度,字符串本身是其最长的子串,子串要求:

只包含1个字母(az,AZ),其余必须是数字;
字母可以在子串中的任意位置;
如果找不到满足要求的子串,如全是字母或全是数字,则返回-1。

代码:
`#include<stdio.h>

int main(){
int Cflag=0,count=0,Nflag=0,countmax=0;
char ch;
do
{
ch=getchar();
if(ch>='A'&&ch<='Z'||ch>='a'&&ch<='z')
{
if(Cflag0)
{
Cflag=1;
count++;
}
else
{
if(count>countmax)
countmax=count;
count=1;
}
}
else if(ch>='0'&&ch<='9')
{
count++;
Nflag=1;
}
}while(ch!='\n');
if(count>countmax)
countmax=count;
if(Nflag
1&&Cflag==1)
printf("%d",countmax);
else
printf("-1");
return 0;
} `

关键点提升:使用if-elseif可以减少判断次数,提高系统运行效率;若为纯字母或者纯数字需要返回-1;使用getcahr()函数比直接获取字符更稳定,否则容易产生逻辑错误。
时间复杂度:O(n)
空间复杂度:O(1)

posted @ 2024-07-17 15:25  jenniferCAI  阅读(68)  评论(0)    收藏  举报