【数据结构】子串、前缀

  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 分钟前
【Spring】常用注解分类整理
java·后端·spring
用户47949283569156 分钟前
React Hooks 的“天条”:为啥绝对不能写在 if 语句里?
前端·react.js
是一个Bug7 分钟前
Java基础20道经典面试题(二)
java·开发语言
Z_Easen10 分钟前
Spring 之元编程
java·开发语言
我命由我1234525 分钟前
SVG - SVG 引入(SVG 概述、SVG 基本使用、SVG 使用 CSS、SVG 使用 JavaScript、SVG 实例实操)
开发语言·前端·javascript·css·学习·ecmascript·学习方法
leoufung25 分钟前
LeetCode 373. Find K Pairs with Smallest Sums:从暴力到堆优化的完整思路与踩坑
java·算法·leetcode
阿蒙Amon26 分钟前
C#每日面试题-委托和事件的区别
java·开发语言·c#
宋情写32 分钟前
java-IDEA
java·ide·intellij-idea
最贪吃的虎41 分钟前
Git: rebase vs merge
java·运维·git·后端·mysql
用户47949283569151 小时前
给客户做私有化部署,我是如何优雅搞定 NPM 依赖管理的?
前端·后端·程序员