/*
https://leetcode.cn/problems/longest-substring-without-repeating-characters/?favorite=2cktkvj
find max string which doesn't contain duplicated chars:
"abcabcbb" -->3 abc
pwwkew --> 3 wke
0 <= s.length <= 5 * 104
s 由英文字母、数字、符号和空格组成
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_CHARS 256
static int alphabet[MAX_CHARS] = {0};
static const char *get_current_unduplicated_string(const char *next)
{
while (*next != '\0') {
alphabet[*next]++;
if (alphabet[*next] > 1)
break;
next++;
}
return next;
}
static int handle_duplicated_char(const char *str, int check_len, char check_char)
{
int i = 0;
for (i = 0; i < check_len; i++) {
alphabet[str[i]] = 0;
if (str[i] == check_char)
break;
}
return (i + 1);
}
static void find_max_unduplicated_string(const char *str)
{
int max = 0;
const char *next = str, *start = str, *pos = str;
while (1) {
const char *dup_pos = get_current_unduplicated_string(next);
int current = (int)(dup_pos - start);
if (current > max) {
max = current;
pos = start;
}
char check = *dup_pos;
if ( check == '\0')
break;
start = start + handle_duplicated_char(start, current, check);
next = dup_pos;
}
printf("\nmax unduplicated string: len=%d, string: ", max);
for (int i = 0; i < max; i++) {
putchar(*(pos + i));
}
}
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("To find the max unduplicated string, please input a string!\n");
return 0;
}
find_max_unduplicated_string(argv[1]);
return 0;
}
查找非重复字符最长子串
于 2023-01-21 20:05:27 首次发布