【数据结构】子串、前缀

  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);
相关推荐
SimonKing2 分钟前
WorkBuddy又推出新的限免模型(Hy4 flash)了,羊毛可以薅起来了
java·后端·程序员
黑土豆5 分钟前
用 drawink 给业务页面加一层画板:从网页批注到无限板书
前端·javascript·github
Rain的Java大神之路15 分钟前
别再死背"三级缓存"了!拿 Spring 7.0.8 源码,把 IoC、AOP、事务、循环依赖四大深水区一次蹚平
java·后端·面试
H H.25 分钟前
Java企业级开发:从框架到工程化实战
java·开发语言·经验分享·其他·课程设计
wno70425 分钟前
springboot整合FastDFS
java·spring boot·后端
恋猫de小郭1 小时前
Flutter 3.50.0 Release 的第一个崩溃,修好了,还没 hotfix
android·前端·flutter
顧棟1 小时前
组件生命周期设计:从硬编码初始化到状态机
java·ide
特立独行的猫A9 小时前
别再用 nohup 了:让应用在后台常驻的正确姿势与 systemd 服务详解
java·后端·python
一起_java9 小时前
技术文章-基于Dify-Agent的智能问答系统设计与实现
java·spring boot·后端·agent·dify
Flynn Liang11 小时前
I/O 密集型高并发实战:Java 服务 10 维优化,从线程打满到 10 万 QPS
java·spring boot·性能优化·高并发·系统设计·虚拟线程·io密集型