字符串最大子串

一道题,求解一个给定字符串的最大子串,
如输入:bbcdebfge的话,
输出为:6及cdebfg
  1. #include"MaxSubStr.h"
  2. //输入一个字符串,输出其最大子串长度,即子串中任两个字符不相同 。
  3. //本程序只能输入字母,空格以及逗号,并且不区分大小写,
  4. //输出为第一个具有最大长度的子串以及其长度。
  5. int chartoi(char c)
  6. {
  7.     if(isalnum(c))
  8.     {
  9.         if(isalpha(c))
  10.             return tolower(c)-'a';
  11.         else
  12.             return c-'0'+26;
  13.     }
  14.     else
  15.         if(isspace(c))
  16.             return 36;
  17.         else if(c==',')
  18.             return 37;
  19.         else
  20.         {
  21.             cout<<"error input char"<<endl;
  22.             exit(0);
  23.         }
  24. }
  25. int substr(char* str, int len)
  26. {
  27.     int A[38]={0};
  28.     int i,j;
  29.     int maxlen=0,templen;
  30.     int beg=0,end=0;
  31.     for(i=0,j=0;i<len,j<len; ++j)
  32.         
  33.     {
  34.         int num=chartoi(str[j]);
  35.         if(A[num]==0)
  36.             A[num]=1;
  37.         else
  38.         {
  39.             A[num]+=1;
  40.             int step;
  41.             for(step=i;step<=j;++step)//
  42.             {
  43.                 int num1=chartoi(str[step]);
  44.                 if(A[num1]>1)
  45.                 {
  46.                     --A[num1];
  47.                     break;
  48.                 }
  49.             }
  50.             i=step+1;
  51.         }
  52.         templen=j-i+1;
  53.         if(templen>maxlen)
  54.         {
  55.             beg=i;
  56.             end=j;
  57.             maxlen=templen;
  58.         }
  59.     }
  60.     for(i=beg;i<=end;++i)
  61.         cout<<str[i];
  62.     cout<<endl;
  63.     return maxlen;
  64. }
  65. void DemoMaxSub()
  66. {
  67.     char str[]="abcdapp";
  68.     cout<<str<<endl;
  69.     cout<<substr(str,strlen(str))<<endl;
  70. }

思路:新建一个标记表,并建立一个一一映射,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:代码来自网络,出处忘了。)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值