// 判断是否有反复字符 // 隐含条件是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 len = strlen(s); while (head < len && tail < len) { if (isInSet(s, head, tail + 1) > -1) { max = max >= (tail - head + 1) ? max : (tail - head + 1); head++; } 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中,如果存在,这阐明有反复,因而左指针右移,并将左指针所指元素删除。我的写法中,用的是原始数组判断元素是否存在,细节解决上和哈希表还是有些区别,没有元素插入与删除,判断是否存在反复没有哈希简略,须要本人遍历。