查找非重复字符最长子串

/*
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值