题目:
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: “pwwkew”
Output: 3
Explanation: 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.
解法一:
基本思路:用双重循环,遍历字符串,用一个数组来记载是否遇到相同的字符。如果遇到,则记录字符串长度,并且开始下一次循环。
C语言代码:
int lengthOfLongestSubstring(char * s){
int i;
int j;
int len = 0;
int res = 0;
for(i=0;s[i]!='\0';i++)
{
int temp[256]={0};
len =0;
for(j=i;s[j]!='\0';j++)
{
int k = s[j];
if(temp[k]!=0)
{
break;
}
else
{
temp[k]=1;
len++;
}
}
if(len>res)
{
res=len;
}
}
return res;
}
执行效率:
执行时间较长,内存占用可还行?
解法二:
思路:只需要完整遍历一次字符串,在遍历的同时,设置2个指针,一个指向当前的字符(i),一个指向重复之后的下一个字符,表示新的不重复的字符串开始的位置(j)。用一个数组来检测是否有相同的字符。如果有相同的字符,则更新的数组以及 j 的指向,并记录当前最长长度。反之,则推进 i ,完成遍历。
C语言实现:
int lengthOfLongestSubstring(char * s){
int i;
int j;
int len = 0;
int res = 0;
int temp[256]={0};
for (i = 0, j = 0; s[i] != '\0';i++ )
{
int k = s[i];
if (temp[k] != 0)
{
if (len > res)
{
res = len;
}
int m;
while (s[j] != s[i])
{
m = s[j];
temp[m] = 0;
j++;
len--;
}
j++;
}
else
{
temp[k] = 1;
len++;
}
}
if(len>res)
{
res=len;
}
return res;
}
效率:
时间效率显著提高,空间效率有所下降