【数据结构】子串、前缀

  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);
相关推荐
不如语冰16 分钟前
AI大模型入门1.1-python基础-数据结构
数据结构·人工智能·pytorch·python·cnn
J_liaty19 分钟前
Spring Security整合JWT与Redis实现权限认证
java·redis·spring·spring-security
EEEzhenliang21 分钟前
CSS知识概括、总结
前端·css
三角叶蕨27 分钟前
【苍穹外卖】day1
java
WAZYY061931 分钟前
通过LocalDateTime判断当前日期是否失效(附Java 中常用的 ISO 格式)
java·iso·日期·localdate·时间处理·日期处理·日期格式
大阳光男孩34 分钟前
ElementUI表格懒加载子级更新数据刷新不生效问题
前端·javascript·elementui
未来之窗软件服务35 分钟前
计算机等级考试—哈希线性探测解答—东方仙盟
数据结构·哈希算法·散列表·计算机软考·仙盟创梦ide·东方仙盟
wy31362282137 分钟前
C#——意框架(结构说明)
前端·javascript·c#
皙然37 分钟前
SpringBoot 自动装配深度解析:从底层原理到自定义 starter 实战(含源码断点调试)
java·spring boot·spring
NE_STOP40 分钟前
SpringBoot3-外部化配置与aop实现
java