【数据结构】子串、前缀

  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);
相关推荐
喝咖啡的女孩3 分钟前
React 合成事件系统
前端
从文处安17 分钟前
「九九八十一难」组合式函数到底有什么用?
前端·vue.js
用户59625857360629 分钟前
戴上AI眼镜逛花市——感受不一样的体验
前端
yuki_uix34 分钟前
Props、Context、EventBus、状态管理:组件通信方案选择指南
前端·javascript·react.js
老板我改不动了35 分钟前
前端面试复习指南【代码演示多多版】之——HTML
前端
panshihao36 分钟前
Mac 环境下通过 SSH 操作服务器,完成前端静态资源备份与更新(全程实操无坑)
前端
日月云棠1 小时前
各版本JDK对比:JDK 25 特性详解
java
hulkie1 小时前
从 AI 对话应用理解 SSE 流式传输:一项 "老技术" 的新生
前端·人工智能
dobym1 小时前
里程碑五:Elpis框架npm包抽象封装并发布
前端
全栈老石1 小时前
手写无限画布4 —— 从视觉图元到元数据对象
前端·javascript·canvas