1.Question:
题意:
有一个字符串,现在让我们求出最大的不重复的连续的子串的长度
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.
2.Solution:
本题有两种思路:
第一种,我们视每一个字母都是一个连续的不重复的子串的开始的话,我们可以利用O(n^2)的时间复杂度遍历每一种情况,然后找到最大的一种情况
这种思路会超时
第二种思路很好想,我一开始就想到是这种的解题思路:
我们定义一个头指针,定义一个尾指针,每一次我们头尾指针确定一个不重复的连续 的子串
一旦我们遇到一个相同的我们就让头指针后移到不重复的位置然后维护我们的最大只存放的变量,知道我们的为指针扫描完整个的字符串
直接输出最大的长度就可以啦
本质上,第二种思路算是一种动态规划,我们的状态就是头尾指针的位置(最大的维护的长度)
状态转移方程就是,每次不重复的话,我们直接的递增
相同的话,位移头指针然后继续
对于判断重复的情况,因为题目限定用字符串的,我们采用256大小的数组散列一下就可以了
3.Code:
int lengthOfLongestSubstring(char* s) {
int max_lengthp=0;
int book[256];
for(int i=0;i<256;i++) book[i]=0;
int i=0;
int j=0;
int length=strlen(s);
while(j<length)
{
if(book[(int)s[j]]==1)
{
while(s[i]!=s[j]) book[(int)s[i++]]=0;
i++;
}
book[(int)s[j]]=1;
j++;
if(j-i>max_lengthp) max_lengthp=j-i;
}
max_lengthp=max_lengthp>(j-i)?max_lengthp:(j-i);
return max_lengthp;
}