题目来源:https://leetcode.com/problems/longest-substring-without-repeating-characters/#/description
Given a string, find the length of the longest substring without repeating characters.
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.
我的C程序:
int lengthOfLongestSubstring(char* s) {
int i,left,right,currlen=1,maxlen=1;
if (s==NULL || *s == 0)
{
return 0;
}
for (left=0,right=left+1; s[right]!='\0'; right++)
{
for (i=right-1; i>=left; i--)
{
if (s[right] == s[i])
{
left = i+1;//以与当前字符相当的下一字符为新起始点
currlen = right-i;
break;
}
else if (i == left)//当前字符比较结束
{
currlen ++;
if (currlen > maxlen)
{
maxlen = currlen;//更新最长长度
}
}
}
}
return maxlen;
}
过程和思路:仍然没有一两次就完成程序,需要调试几次才完善。该题可以用到一点KMP算法的思想,当取一个新字符逐个和前面字符比较遇到相当时,
将起始点更新到相等字符的下一个可以节省不少时间。
结论:经过连续几次编程练习,思路还是比之前略微好了些,但是仍存在边写程序边想的习惯,在开始之前不能考虑得更全面。