【数据结构】子串、前缀

  1. 子串 (Substring)

    • 字符串中连续的一段字符序列,例如 "abc""abcd" 的子串。

    • 特点必须连续,顺序不可改变

  2. 子序列 (Subsequence)

    • 字符串中不连续但保持顺序的字符序列,例如 "acd""abcd" 的子序列。
  3. 前缀 (Prefix)

    • 字符串开头的子串,例如 "a", "ab", "abc" 都是 "abcde" 的前缀。
  4. 后缀 (Suffix)

    • 字符串结尾的子串,例如 "e", "de", "cde""abcde" 的后缀。
KMP 前缀函数(计算 next 数组)
复制代码
#include <stdlib.h>
#include <string.h>

int* compute_prefix_function(const char* pattern) {
    int n = strlen(pattern);
    int* next = (int*)malloc(n * sizeof(int));
    if (next == NULL) return NULL;

    int j = 0;
    next[0] = 0;
    for (int i = 1; i < n; i++) {
        while (j > 0 && pattern[i] != pattern[j]) {
            j = next[j - 1];
        }
        if (pattern[i] == pattern[j]) {
            j++;
        }
        next[i] = j;
    }
    return next; // 调用者需自行 free 释放内存
}

// 示例用法:
// const char* pattern = "ababaca";
// int* next = compute_prefix_function(pattern);
// free(next);
滑动窗口(最长无重复子串)
复制代码
int longest_unique_substring(const char* s) {
    int max_len = 0;
    int left = 0;
    int char_map[256]; // 假设字符为 ASCII 码
    memset(char_map, -1, sizeof(char_map)); // 初始化所有字符位置为 -1

    for (int right = 0; s[right] != '\0'; right++) {
        char c = s[right];
        if (char_map[c] >= left) {
            left = char_map[c] + 1;
        }
        char_map[c] = right;
        int current_len = right - left + 1;
        if (current_len > max_len) {
            max_len = current_len;
        }
    }
    return max_len;
}

// 示例用法:
// const char* s = "abcabcbb";
// int result = longest_unique_substring(s);
相关推荐
闻哥1 分钟前
从测试坏味道到优雅实践:打造高质量单元测试
java·面试·单元测试·log4j·springboot
smileNicky1 分钟前
统一网关的登录流程总结
java
计算机程序设计小李同学14 分钟前
基于 Spring Boot + Vue 的龙虾专营店管理系统的设计与实现
java·spring boot·后端·spring·vue
广州华水科技15 分钟前
单北斗GNSS在桥梁形变监测中的应用与技术进展分析
前端
我讲个笑话你可别哭啊16 分钟前
鸿蒙ArkTS快速入门
前端·ts·arkts·鸿蒙·方舟开发框架
CherryLee_121018 分钟前
基于poplar-annotation前端插件封装文本标注组件及使用
前端·文本标注
LiZhen79818 分钟前
SpringBoot 实现动态切换数据源
java·spring boot·mybatis
特立独行的猫a25 分钟前
C++轻量级Web框架介绍与对比:Crow与httplib
开发语言·前端·c++·crow·httplib
周航宇JoeZhou27 分钟前
JB2-7-HTML
java·前端·容器·html·h5·标签·表单
代码小库29 分钟前
【课程作业必备】Web开发技术HTML静态网站模板 - 校园动漫社团主题完整源码
前端·html