Leetcode 3. 无重复字符的最长子串(C语言)

3. 无重复字符的最长子串

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

示例 1:

输入: "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

示例 2:

输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

示例 3:

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

解题思路

  1. 字符串为0或1的时候可以直接返回对应结果。
  2. 设一个max_len = 0,记录字符串中出现的最长不重复子串的长度。
  3. 使用一个count_len记录正在访问的子串的最大长度。
  4. 类似KMP算法的思想,使用repeat_loc数组记录已访问字符的下一个位置ipos+1
  5. 使用桶排序记录已访问字符,如果正在访问的字符是已访问字符,那么将访问位置repeat_loc[s[ipos]]
  6. 如果正在访问的字符是已访问字符,将count_lenmax_len比较并根据条件赋值,重置count_len = 1,并置空桶排序记录和位置记录。

解题代码(C语言)

int lengthOfLongestSubstring(char *s){
    int str_len = strlen(s);
    if(str_len == 0) return 0;
    if(str_len == 1) return 1;
    int maxn_len = 0,count_len = 1,ipos = 1;
    int count_setp[255];
    int repeat_loc[255];
    memset(count_setp,0,sizeof(count_setp));
    memset(repeat_loc,0,sizeof(repeat_loc));
    count_setp[s[0]]++;
    repeat_loc[s[0]]=1;
    while(ipos < str_len)
    {
        if(s[ipos]!=s[ipos-1] && count_setp[s[ipos]] == 0)
        {
            count_len++;
            count_setp[s[ipos]]++;
            repeat_loc[s[ipos]] = ipos+1;
            ipos++;
        }
        else
        {
            maxn_len = maxn_len > count_len ? maxn_len : count_len;
            count_len = 1;
            memset(count_setp,0,sizeof(count_setp));
            ipos = repeat_loc[s[ipos]];
            memset(repeat_loc,0,sizeof(repeat_loc));
            count_setp[s[ipos]]++;
            repeat_loc[s[ipos]]=ipos+1;
            ipos++;
        }
    }
    maxn_len = maxn_len > count_len ? maxn_len : count_len;
    return maxn_len;c
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章