一道题,求解一个给定字符串的最大子串,
如输入:bbcdebfge的话,
输出为:6及cdebfg
- #include"MaxSubStr.h"
- //输入一个字符串,输出其最大子串长度,即子串中任两个字符不相同 。
- //本程序只能输入字母,空格以及逗号,并且不区分大小写,
- //输出为第一个具有最大长度的子串以及其长度。
- int chartoi(char c)
- {
- if(isalnum(c))
- {
- if(isalpha(c))
- return tolower(c)-'a';
- else
- return c-'0'+26;
- }
- else
- if(isspace(c))
- return 36;
- else if(c==',')
- return 37;
- else
- {
- cout<<"error input char"<<endl;
- exit(0);
- }
- }
- int substr(char* str, int len)
- {
- int A[38]={0};
- int i,j;
- int maxlen=0,templen;
- int beg=0,end=0;
- for(i=0,j=0;i<len,j<len; ++j)
- {
- int num=chartoi(str[j]);
- if(A[num]==0)
- A[num]=1;
- else
- {
- A[num]+=1;
- int step;
- for(step=i;step<=j;++step)//
- {
- int num1=chartoi(str[step]);
- if(A[num1]>1)
- {
- --A[num1];
- break;
- }
- }
- i=step+1;
- }
- templen=j-i+1;
- if(templen>maxlen)
- {
- beg=i;
- end=j;
- maxlen=templen;
- }
- }
- for(i=beg;i<=end;++i)
- cout<<str[i];
- cout<<endl;
- return maxlen;
- }
- void DemoMaxSub()
- {
- char str[]="abcdapp";
- cout<<str<<endl;
- cout<<substr(str,strlen(str))<<endl;
- }
思路:新建一个标记表,并建立一个一一映射,a(A)-z(Z),0-9,'',','分别对应0-25,26-35,36和37来标记并记录一个字符出现的次数。
当str[j]为一新字符的话,修改标记。并修改maxlen,
否则,在str[i]-str[j]之间找到与str[j]相同的字符,并置i为相同字符的后一个字符,并置i=step+1;不修改maxlen
(ps:代码来自网络,出处忘了。)