#3 Longest Substring Without Repeating Characters

来源:互联网 发布:淘宝评价语30字 编辑:程序博客网 时间:2024/05/20 20:17

题目链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/


Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.


//O(n)时间复杂度。 双指针s,p遍历数组,分别记录不重复子序列的头部和尾部int lengthOfLongestSubstring(char* s) {    if(*s == '\0')          return 0;    int maxLen = 1;    char *p;    int exist[256] = {};        //标志当前考察子序列所包含的字母    p = s + 1;    exist[*s] = 1;    while(*p) {        while(*p && !exist[*p]) {   //p遍历数组,直到碰到与s、p之间有重复的字母,同时记录遍历过的字母            exist[*p] = 1;            ++p;        }        if(p - s > maxLen)  //考察子序列大于记录最大长度,更新最大长度            maxLen = p - s;        if(*p == '\0')              break;        while(*s != *p) {   //更新子序列的头部,新头部在与p处字母相同的后面(一直保证s、p之间的字母都不想等)            exist[*s] = 0;      //把子序列中删去的字母标记重新            ++s;        }        ++s;        ++p;    }    return maxLen;}


0 0
原创粉丝点击