您的位置:首页 > 职场人生

微软:求最大连续递增数字串/时钟问题

2013-09-23 14:10 423 查看
11、求最大连续递增数字串(如“ads3sl456789DF3456ld345AA”中的“456789”)

思路:记录当前最长长度CurMaxLen和当前最长数字串的开始索引Begin.和全局最长长度Max比较,如果当前长度更长,则更新Max和全局开始索引。直至到结尾。

#include<iostream>
using namespace std;

void LongestIncreaseStr(char* str)
{
if(str==NULL)
return ;
int len=strlen(str);
int max=0;
int CurMaxLen=0;//初始长度=0
int first=0;
for(int i=0;i<len-1;i++)
{
if(str[i+1]>str[i]&&str[i]>='0'&&str[i]<='9'&&str[i+1]>='0'&&str[i+1]<='9')
{
CurMaxLen++;
}
else
{
if(CurMaxLen>max)
{
max=CurMaxLen+1;
first=i-CurMaxLen;
}
CurMaxLen=0;
}
}
//处理末尾是数字串的情况abcd12345
if(CurMaxLen>max)
{
max=CurMaxLen+1;
first=len-max;
}
cout<<first<<endl;
for(int i=first;i<first+max;i++)
cout<<str[i];
cout<<endl;
}

int main()
{
char* str=NULL;
LongestIncreaseStr(str);
return 0;
}

上述代码有误,在处理abc1da时有误,仅当反面教材。

以下是新代码:

#include<iostream>
using namespace std;
//abcd1234abd346894abc
//abcd1234abd346894
//abcd1
//1dfa
//abcd1234a
bool isNumber(char c)
{
return ('0' <=c && c<='9');
}
int LIS(char *str)
{
int i = 0,j = 0,max = 0,len=strlen(str);
char ch;
while( i<len )
{
while(i < len && !isNumber(str[i]))
++i;
j = i,ch = str[i];
while(j < len && isNumber(str[j]) && ch <= str[j])
{
ch = str[j];
++j;
}
if( j-i > max)
max = j-i;
i = j;
}
return max;
}
int main()
{
char str[100];
while( gets(str)!=NULL)
cout << LIS(str) << endl;
return 0;
}

时钟问题参考资料:

http://wenku.baidu.com/view/7fd92105e87101f69e31959a.html

http://baike.baidu.com/view/1389109.htm

http://www.cnblogs.com/doubleming/archive/2012/10/17/2727502.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息