【数据结构】子串、前缀

  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);
相关推荐
荣码2 分钟前
多模态应用入门:让AI看懂图片再回答问题,我踩了4个坑
java·python
不可能片场2 分钟前
工程实践 管道截断让证据写不出来
前端·electron
Swot8 分钟前
mermaid 子图跨边:direction 失效与并行连接
前端
用户0723670666018 分钟前
接口级配 50%、方法级配 30%,这个方法实际切多少
java·dubbo
淘源码A22 分钟前
智能预问诊系统源码,基于SpringBoot、MyBatis-Plus、uni-app等技术栈,开箱即用
java·spring boot·源码·二次开发·电子病历·预问诊·智能预问诊
夏幻灵26 分钟前
Java 学习日记:多态
java·开发语言·学习
挖掘狂人29 分钟前
外包与大厂前端的差距在哪?
前端·代码规范·前端工程化
apcipot_rain30 分钟前
C++转Java日记(19)
java·开发语言
JAVA面经实录91740 分钟前
AI 辅助写单元测试
java·人工智能·单元测试·ai编程
陈随易44 分钟前
2027汽车制造业8大ERP选型参考:主流厂商对比与优缺点分析
前端·后端·程序员