2024-03-19 02:45:09 +08:00

46 lines
1.3 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/**
* https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/description/
* 无重复字符的最长子串
*/
int lengthOfLongestSubstring(char *s)
{
//初始化变量
int len = strlen(s);
int *hash = malloc(128 * sizeof(int));
memset(hash, -1, sizeof(int) * 128);
int maxlen = 0, nowlen = 0;
for (int i = 0; i < len; i++, nowlen++)
{
if (hash[s[i]] != -1 && hash[s[i]] >= i - nowlen) //利用一个数组增加来判断是否重复
{
if (nowlen > maxlen)
{
maxlen = nowlen;
}
//上一次位置hash[s[i]现在这一次位置i
//重新计算长度 nowlen=i-hash[s[i]]-1
nowlen = i - hash[s[i]] - 1;
}
hash[s[i]] = i;//记录位置
}
if (nowlen > maxlen) //最后的没有判断
{
maxlen = nowlen;
}
return maxlen;
}
int main()
{
printf("%d\n", lengthOfLongestSubstring("abcabcbb"));
printf("%d\n", lengthOfLongestSubstring("aab"));
printf("%d\n", lengthOfLongestSubstring("dvdf"));
printf("%d\n", lengthOfLongestSubstring("bbbbb"));
printf("%d\n", lengthOfLongestSubstring("pwwkew"));
getchar();
return 0;
}