您的位置:首页 > 编程语言 > C语言/C++

LeetCode-3-Longest Substring Without Repeating Characters(C语言实现)

2017-12-18 05:46 411 查看
(自己推导实现的并不标准的KMP算法)

int lengthOfLongestSubstring(char* s) {

    int length = 0;                    
//记录最大长度

    int this_len =
1;                   //记录当前取到的最大长度

    int cmp_times =
0;                  //记录当前从head开始的和tail数据正在进行的比较次数

    char *str_head, *str_tail, *cmp;   
//标记遍历子串的head、tail、正在和tail数据比较的子串内部数据的位置

    str_head = s;                       //初始化head:字符串第一个数据

    str_tail = s + 1;                  
//初始化tail:字符串第二个数据

    

    //特殊情况处理(没有字符或只用一个字符)

    if(s[0] ==
'\0')

        return 0;

    if((++s)[0] ==
'\0')

        return 1;

    

    //普通情况KMP遍历

    while(str_tail[0] !=
'\0')          //当tail没有超出字符串进入循环

    {

        cmp = str_head;                 //从head开始比较数据,依次向后遍历

        //满足不重复条件:while循环,每次cmp后移一位;满足不等条件的位数+1

        while(cmp[0] != str_tail[0])

        {

            ++cmp;

            ++cmp_times;

        }

        //出现重复:分两种情况讨论

        //1、cmp和tail重合(该子串满足条件,延续tail判别):tail后移一位;this_len+1;更新length、this_len、cmp_times;对新串遍历

        if(cmp == str_tail)

        {

            ++str_tail;

            ++this_len;

            length = (length > this_len) ? length : this_len;

            cmp_times = 0;

            continue;

        }

        //2、子串内部有元素与tail相等(该子串不满足条件,对新串判别):head移到tmp+1位置;更新length、this_len、cmp_times;对新串遍历

        if(cmp[0] == str_tail[0])

        {

            str_head = ++cmp;

            length = (length > this_len) ? length : this_len;

            this_len -= (cmp_times + 1);

            cmp_times = 0;

            //细节处理:本算法设置初始条件是tail后置head一位,若出现连续元素重复,更新指针位置时会出现head、tail重合,需手动处理

            if(str_head == str_tail)

            {

                ++str_tail;

                ++this_len;

            }

            continue;

        }

    }

    return length;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: