LeetCode 3.Longest Substring Without Repeating Characters c语言版

问题描述:

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

解法1:暴力法

从前向后循环字符串,分别求出每个字符开始它所对于的最长不重复字串,例如abcdab  a对应的最长字串4,同理b----4, c----4, d----3,a'(第二个a)-----2,b'(第二个b)----1

int lengthOfLongestSubstring(char* s) 
{
    int i, j, k, isRepeat;
    int temp, maxlen = -1;
    int len = strlen(s);
    if (len == 0) return 0;
    for(i = 0; i < len; i++) //循环每个字符
    {
        j = i + 1;
        temp = 1;
        isRepeat = 0;//出现重复字符就置1
        while(j < len && isRepeat == 0)//从i的下一个字符开始统计s[i]字符的最长不重复字串
        {
            k = i;
            while(k < j)//j和i~j-1的每个字符做比较,不等才能字串长+1
            {
                if(s[j] != s[k])    k++;
                else{
                    isRepeat = 1;
                    break;
                }
            }
            if(k == j){//当前j所对应字符第一次出现
                j++;
                temp++;
            }          
        }
        maxlen = maxlen > temp?maxlen:temp;
    }
    return maxlen;
    
}

解法2.

定义一个辅助数组,tabels[128] ,记录是否有重复字符

int lengthOfLongestSubstring(char* s) {
    int maxlen = 0,currlen = 0;
    int table[128], i, j, start = 0;
    memset(table, 0, sizeof(table));
    for (i = 0; s[i] != '\0'; ++i){ // 只要字符串每结束就循环
        if( (++table[s[i]]) == 2 ){ // 只要是第一次出现的字符,就将table[s[i]]置为1,已出现则重复,table[s[i]]==2
            if (currlen > maxlen){ 
                maxlen = currlen;
            }
            for(j = start; j < i; ++j){ 
                if (s[j] == s[i]){ // 出现重复位置了,比如abcdcd  s[2] == s[4]
                    table[s[j]] = 1;
                    start = j+1; // start记录出现重复的字符的后一个位置,比如还有字符串abcdcd,start = 3
                    break;
                }else{
                    --currlen;
                    table[s[j]] = 0;// 还拿字符串abcdcd举例,将tables['a'] = 0,tabels['b']=0;方便下一次查找
                }
            }
        }else{ // 没有重复的字出现,累计子串长度
            ++currlen;
        }
    }
    if (currlen > maxlen){ //全部字符不重复
        maxlen = currlen;
    }
    return maxlen;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值