最长字符串

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define MAX(a ,b) ((a)<(b)? (b):(a))

int lengthOfLongestSubstring2(char * s)
{
    int hash[127] = {0};

    int left = 0,right = 0,max =0;

    while(s[right])
    {
        if (hash[s[right]] && (left < hash[s[right]]))
        {
            left = hash[s[right]] ;
        }
        
        hash[s[right]] = right + 1;
        max = MAX(max,(right - left +1));
        right++;
    }
    return max;
}

int lengthOfLongestSubstring3(char * s)
{
    int hash[127] = {0};

    int left = 0,right = 0,max =0;

    while (s[right])
    {
        if (hash[s[right]]==0)
        {
            hash[s[right++]]++;
        }
        else
        {
            hash[s[left++]]--;
        }
        max = MAX(max,(right-left));        
    }
    return max;
    
}

int main(int *argc,char *argv[])
{
    char * s ="dbbabcabc";
    int temp =0;

    temp = lengthOfLongestSubstring1(s);
    printf("algorithm1 temp =%d\n",temp);
    
    temp = lengthOfLongestSubstring2(s);
    printf("algorithm2 temp =%d\n",temp);
   
    temp = lengthOfLongestSubstring3(s);
    printf("algorithm3 temp =%d\n",temp);

}

使用hash表,记录字符出现的次数,用左右指针制造滑动窗口。如果hash为0,右指针增加,并且对应的hash表加一;如果hash不为0,左指针增加,hash减一。记录最长字符串长度。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值