// 判断是否有重复字符
// 隐含条件是end之前的字符没有重复的,只需判断end是否重复即可
int isInSet(char *str, int start, int end) {
for (int i = start; i < end; i++) {
if (str[i] == str[end]) {
return i;
}
}
return -1;
}
int lengthOfLongestSubstring(char * s){
// 定义初始头下标及尾下标
int head = 0;
int tail = 0;
int max = 0;
int index;
int len = strlen(s);
while (tail < len) {
index = isInSet(s, head, tail + 1);
if (index > -1) {
max = max >= (tail - head + 1) ? max : (tail - head + 1);
head = index + 1;
} else {
max = max >= (tail - head + 1) ? max : (tail - head + 1);
tail++;
}
}
return max;
}
执行用时:12 ms, 在所有 C 提交中击败了39.22%的用户
内存消耗:5.9 MB, 在所有 C 提交中击败了18.22%的用户算法:滑动窗口法
我的实现性能一般,大家可以参考参考。
主要是鉴于滑动窗口的思想来实现的,C中没有hashset,因此用数组来替代。并且哈希表判断元素是否存在于集合在中,如果不存在,则右指针右移,并将元素添加到set中,如果存在,这说明有重复,因此左指针右移,并将左指针所指元素删除。我的写法中,用的是原始数组判断元素是否存在,细节处理上和哈希表还是有些区别,没有元素插入与删除,判断是否存在重复没有哈希简单,需要自己遍历。
int lengthOfLongestSubstring(char * s){
// 定义初始头下标及尾下标
int head = 0;
int tail = 0;
int max = 0;
int len = strlen(s);
while (tail < len) {
for (int i = head; i < tail; i++) {
if (s[tail] == s[i]) {
max = tail - head > max ? tail - head : max;
head = i + 1;
break;
}
}
tail++;
max = tail - head > max ? tail - head : max;
}
return max;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。