华为机试——求字符串中最长无重复子串

题目:找到一个字符串中的一个连续子串,这个子串内不能有任何两个字符是相同的,并且这个子串是符合要求的最长的。

例如:abcdeab,这个字符串有很多不重复子串,比如:abcde, bcdea, cdeab都是不重复子串,而且都是最长的。

解题思路: 对这个字符串构造后缀数组,在每个后缀数组中,寻找没有重复字符的最长子串

#include<iostream>
#include<cstdio>
using namespace std;
int longestlen(char *p)
{
    int hash[256]={0};
    int len=0;
    while(*p && !hash[*p])
    {
        hash[*p]=1;
        ++len;
        ++p;
    }
    return len;
}

//使用后缀数组解法
int max_unique_substring(char *str)
{
    int maxlen=0;
    int begin=0;
    char *a[1000];
    int n=0;
    while(*str!='\0')
    {
        a[n++]=str++;
    }
    for(int i=0;i<n;i++)
    {
        int templen=longestlen(a[i]);
        if(templen>maxlen)
        {
            maxlen=templen;
            begin=i;
        }
    }

    printf("%.*s\n",maxlen,a[begin]);
    return maxlen;
}

int main()
{
    char str[100];
    cin.getline(str,100);
    cout<<max_unique_substring(str)<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值