题目链接: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;
}
本文介绍了一种使用双指针法解决 LeetCode 上的最长无重复字符子串问题的算法,时间复杂度为 O(n),适用于字符串处理场景。
298

被折叠的 条评论
为什么被折叠?



