Problem: Given a string, please get the length of the longest substring which does not have duplicated characters. Supposing all characters in the string are in the range from ‘a’ to ‘z’.
妙处在于如何正确定义子问题。
参考:http://codercareer.blogspot.com/2013/11/no-49-longest-substring-without.html
/* Copyleft: Ming Lin <minggr@gmail.com> */
#include <stdio.h>
char *position(char *str, int len, char c)
{
while (len > 0) {
if (c == *str)
return str;
len--;
str--;
}
return NULL;
}
int longest_substring(char *str)
{
int len, maxlen;
char *tmp;
len = maxlen = 0;
while (*str) {
if (len == 0) {
maxlen = len = 1;
str++;
continue;
}
tmp = position(str-1, len, *str);
if (!tmp)
len++;
else
len = str - tmp;
if (len > maxlen)
maxlen = len;
str++;
}
return maxlen;
}
int main()
{
char str[] = "abazckbLMNLb";
printf("%s\n", str);
printf("longest_substring: %d\n", longest_substring(str));
return 0;
}
本文介绍了一个算法,用于计算给定字符串中不包含重复字符的最长子串长度。通过定义子问题并使用特定函数实现,该算法有效地解决了这一挑战。
147

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



