实用算法实现-第 8 篇 后缀树和后缀数组 [4 最长回文子串]

实用算法实现-第8篇 后缀树和后缀数组 [1简介] 8.1    后缀树 一棵后缀树包含一个指定文本的所有后缀,对于在一个长度为N的文本中查找一个长度为M的子字符串,一个后缀树仅仅需要M次比较,而这个比较次数是查找该字符串所需要的最小比较次数。 后缀树有以下特征:一条边可以表示文本的任何非空子串,每个非终端节点,除了根节点,必须至少有两个孩子边,兄弟边表示的子串必须开始于不同的字符。 ababa所对应的后缀树如下所示: 后缀树可以解 阅读详情

8.5    最长回文子串

定义字符串S的逆序为S’,有S’[i]=S[n - i - 1](0 ≤ i < len(S),下文所有i处于这个区间内)。其中len(S)为S的长度。如果S和S’相同,则称S为回文串(Palindrome)。S的最长回文子串就是S的所有子串中是回文串且长度最长的字符串。

定义Suffix(S, i)为S以S[i]开头且包含S[i]的后缀字符串。

定义Prefix(S, i)为S以S[i]结尾且包含S[i]的后缀字符串。

令n = Len(S)

可知有如下性质:

1. Len(S’) = Len(S) = n;

2. Len(Suffix(S, i)) = Len(S) - i;

3. Len(Prefix(S, i)) = i;

4. Prefix(S, i) = Suffix’(S’, len(S) - i- 1);

5. Suffix(S, i) = Prefix’(S’, len(S) - i- 1);

6. (S’)’ = S.

要求S的最长回文子串,可以对i在区间[0, len(S))内枚举,找出以S[i]为中心字符的最长回文子串。所有这些回文子串中最长的那个就是S的最长回文子串。

求以S[i]为中心字符的最长回文子串的问题可以描述为:

求一对下标(j, k),满足下列条件:

1. 0 ≤ j ≤ i, i ≤ k < len(S)。因为j,k是S的下标,且一个比i小,一个比i大。

2. i - j = k - i = x。因为所求字符串以S[i]为中心字符。

3. Suffix’(Prefix(S, i), j) = Prefix(Suffix(S,i), k - i) = T。因为所求字符串为回文字符串。

4. x最大

可知在满足条件1的情况下,有:

Suffix’(Prefix(S, i), j)

= Prefix’’(Prefix’(S, i), Len(Prefix(S,i)) - j - 1)           性质5

= Prefix’’(Prefix’(S, i), i + 1 - j - 1)                     性质3

= Prefix(Prefix’(S, i), i - j)                                     性质6

= Prefix(Suffix’’(S’, Len(S) - i - 1), i- j)                 性质4

= Prefix(Suffix(S’, Len(S) - i - 1), i -j)                  性质6

= Prefix(Suffix(S’, Len(S’) - i - 1), i -j)                  性质1

= Prefix(Suffix(S’, n - i - 1), i - j)

所以第三个条件转化为:

Prefix(Suffix(S’, n - i - 1), i - j) = Prefix(Suffix(S,i), k - i)

又由于有条件2,进一步写为:

Prefix(Suffix(S’, n - i - 1), x) =Prefix(Suffix(S, i), x) = T

观察该条件,可知T是Suffix(S, i)和Suffix(S’, n - i - 1)的公共前缀。进一步地,要满足条件4,使x最大,就是使得公共前缀T最长。该最大公共前缀就是所求的以S[i]为中心字符的最长回文子串。

而求一个串的两个后缀的最长公共前缀正是后缀数组所擅长的事情,后缀数组可以在线性的预处理时间后支持O(1)的LCP询问。

所以求以S[i]为中心字符的最长回文子串的方法即为:构建字符串W = S?S',其中?是S的字符表中不存在的字符。在W中,S[i]对应W[i],S'[n - i - 1]对应W[n + 1 + n - i - 1] = W[2n - i]。故此SA[rank(i)]和SA[rank(2n - i)]的最长公共前缀就是最长回文子串,LCP(rank(i), rank(2n- i))就是最长回文子串的长度max(x)。

8.6    实例

8.6.1   最长公共子串

       PKUJudgeOnline, 3450, Corporate Identity.

       PKUJudgeOnline, 3080, Blue Jeans.

8.6.2   两个串的最长公共子串

       PKUJudgeOnline, 2774, Long Long Message.

本文章欢迎转载,请保留原始博客链接http://blog.youkuaiyun.com/fsdev/article

后缀数组原理及应用详解 后缀数组原理及应用详解      在pongba的讨论组上看到一道Amazon的面试题:找出给定字符串里的最长回文。例子:输入XMADAMYX。则输出MADAM。这道题的流行解法是用后缀树(Suffix Tree)。这坨数据结构最酷的地方是用它能高效解决一大票复杂的字符串编程问题:  1.在文本T里查询T是否包含子串P(复杂度同流行的KMP相当)。 2.文本T里找出最长重复子串。比如ab 阅读详情

相关推荐

Pytorch实现softmax多分类

PyTorch实现softmax多分类

天涯雨的博客 1388

字符串-后缀树和后缀数组详解

后缀树和后缀数组可以解决大部分字符串问题。光速从入门到放弃,看这一篇就够了。 例题: HDU-1403最长公共子串 洛谷P2408 不同子串个数 HDU-5769Substring

有一分热,发一分光。 4990

Isaacgym使用操作指南

Isaac Gym 是一个强大的仿真工具,特别适合那些需要进行大规模并行仿真和训练的机器人和强化学习任务。通过 GPU 加速、深度学习集成和丰富的物理仿真能力,Isaac Gym 能够显著提高仿真和训练效率,是机器人学和 AI 研究中的一大利器。

Tony Wey的博客 1万+

后缀树与最长回文子串

后缀树与最长回文子串 首先引入求最长回文子串的问题: 回文串:正反一样的字符串. 如ABCDCBA,反过来是还是ABCDCBA.   回文子串:DABCAEA中有两个回文子串(不包括长度为1的),即ABCA,AEA. 长度ABCA>AEA.   那么字符串DABCAEA的最长回文子串就是ABCA.   解决方法: 1.      遍历所有的子串.  长度N的字符串,共

ice110956的专栏 5383

DB2__基本概念——联邦

建立联邦 优点:优点是数据仍然保留在原来的存储位置,而不必建立一个集中的式数据仓储。  缺点:数据联邦查询反映会慢,不适合频繁查询,而且容易出现锁争用和资源冲突等问题 建立联邦表步骤 前提条件:知道两个数据库的ip,用户名,密码及被连数据库的版本 eg:  数据库  qqdb  ip: 22.5.225.225   端口:50000    密码:123456        数据库   ...

qq_38569524的博客 1255

【STK】手把手教你利用STK进行进行光电红外仿真02-STK/EOIR模块属性之一 传感器选项设置

EOIR传感器可以从空间几何属性、光谱属性、光学属性、辐射属性四个方面进行设置,并且可以设置信号传播路径中的大气特性,包括大气模型、气溶胶模型、气象学可见性和大气湿度。在定义EOIR传感器时,需要Sensor——Definition属性页中,将Sensor Type设置为EOIR。单击下面的按钮打开传感器的EOIR配置页,可以对传感器的属性进行配置,此外,还可以在场景中视情况添加相关的中心体。路径辐射损耗影响上述特性的计算,计算的结果考虑了传感器、目标位置的影响,但是还没考虑地球临边背景的影响。

weixin_44184852的博客 3201

字符串相关处理kmp,前缀数,后缀树,后缀数组,最长回文串,最长重复字串,最长非重复字串

1. 最长回文串 一般用后缀数组或者后缀树可以解决, 用此方法:http://blog.youkuaiyun.com/v_july_v/article/details/6897097 预处理后缀树,使得查询LCA的复杂度为O(1)。这步的开销是O(N),N是单词S的长度 ;对单词的每一位置i(也就是从0到N-1),获取LCA(S(i), S‘(N-i-1)) 以及LCA(S(i), S’(n-i

chivalry 3167

DeepSeek-R1 论文阅读 DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning

和。这些模型的核心创新点是通过强化学习(Reinforcement Learning, RL)来提升大型语言模型(LLM)的推理能力,而没有依赖传统的监督微调(Supervised Fine-Tuning, SFT)作为预训练的步骤。是一种通过大规模强化学习直接训练的模型。它在推理能力上表现出色,能够自然地展现出许多强大且有趣的推理行为。但它也有一些问题,比如可读性差和语言混合。这意味着模型在生成文本时,有时会显得不太清晰,或者不一致地使用不同语言。为了解决这些问题并进一步提升推理能力,研究者提出了。

CSPhD-winston的博客 1840

【dp/后缀树】最长回文串、最长重复回文串、最长非重复回文串。。

DP: k = i + min

一地鸡毛 932

在 VS Code 里配置 SAP Joule for Developers 的 ABAP AI side-by-side 能力

摘要: 随着ABAP开发工具链的演进,VS Code逐渐融入ABAP开发流程,SAP Joule for Developers的ABAP AI能力通过side-by-side模式(基于BTP中央服务)为多系统开发提供统一AI支持。该模式避免了各ABAP后端独立升级AI能力的碎片化问题,由管理员配置BTP订阅URL后,开发者可在ADT或VS Code中全局调用。实际落地需注意角色分工(管理员配置服务,开发者填写URL)、AI units资源规划及配置细节(如区分全局与项目级设置)。建议将Joule URL纳入

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 120

全能媒体工具深度测评(下篇一):AI图文生成+全能解压+图片去文字,一键搞定素材精修

解压50多种格式,文生图,图生图

cs821984831的博客 40

后缀树建立 java_实用算法实现-第 8 篇后缀树和后缀数组 [4 最长回文子串]

8.5 最长回文子串定义字符串S的逆序为S’,有S’[i]=S[n - i - 1](0 ≤ i < len(S),下文所有i处于这个区间内)。其中len(S)为S的长度。如果S和S’相同,则称S为回文串(Palindrome)。S的最长回文子串就是S的所有子串中是回文串且长度最长的字符串。定义Suffix(S, i)为S以S[i]开头且包含S[i]的后缀字符串。定义Prefix(S,...

weixin_26736139的博客 170

模拟量输入功能块 S_ITR(Easy系列PLC完整ST源代码)

IN Input INT 输入数字量 1IN ISH INT 输入数字量上限 2IN ISL INT 输入数字量下限 3IN OSH REAL 输出工程量上限 4IN OSL REAL 输出工程量下限 5OUT OUTPUT REAL 输出工程量 6VAR temp1 REAL 临时变量1 7VAR temp2 REAL 临时变量2 8。

RXXW_Dor的博客 716

后缀树和后缀数组

后缀树和后缀数组

yejing's utopia 1161

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

字符串处理【后缀数组】 - 原理2 后缀数组

字符串处理【后缀数组】 - 原理2 后缀数组

代码改变世界 1647

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

《力扣题库(C):第5题 (最长回文子串)》

第五题:最长回文子串 给你一个字符串 s,找到 s 中最长的回文子串 示例 1: 输入:s = "babad" 输出:"bab" 解释:"aba" 同样是符合题意的答案 示例 2: 输入:s = "cbbd" 输出:"bb" 示例 3: 输入:s = "a" 输出:"a" 示例 4: 输入:s = "ac" 输出:"a" 提示: 1 <= s.length <= 1000 s 仅由数字和英文字母(大写和/或小写)组成 ...

yexiang优快云的专栏 669

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

后缀数组

在定义后缀树(Suffix Tree)时,我们给出了一段简洁的描述: A suffix tree is a compressed trie for all the suffixes of a text. 后缀数组(Suffix Array)的定义也同样简洁: A suffix array is a sorted array of all suffixes of a text. ...

weixin_33781606的博客 97

后缀数组(百科理论分析不给力,还有错误)

图估计会挂,真正感兴趣的童鞋自己去原文中看吧 原文:http://hi.baidu.com/%B4%F3%D5%AC%C0%C7/blog/item/e687d9862058d526c65cc3e8.html 后缀数组 安徽省芜湖市第一中学 许智磊 【摘要】   本文介绍后缀数组的基本概念、方法以及应用。   首先介绍O(nlogn)复杂度构造后缀数组的倍增算法,接着介绍了配合后缀数组

cx351864995的专栏 850

【经典数据结构】后缀数组

  转自:http://www.acmerblog.com/suffix-array-6150.html   在字符串处理当中,后缀树和后缀数组都是非常有力的工具,其中后缀树大家了解得比较多,关于后缀数组则很少见于国内的资料。其实后缀数组是后缀树的一个非常精巧的替代品,它比后缀树容易编程实现,能够实现后缀树的很多功能而时间复杂度也不太逊色,并且,它比后缀树所占用的空间小很多。   后缀树...

weixin_30539835的博客 108

字符串公共串

一、找出最长公共子序列的长度 题:求字符串str1,str2的最长公共子序列的长度(可以不连续)。 解:定义二元函数函数f(m,n):分别以str1[m],str2[n]结尾的连续公共子序列的长度 而对于f(m,n) 有以下两种情况 1.str1[m] != str2[n],则有f(m,n) = max(f(m-1,n), f(m, n-1)) 2.str

hepeng597的专栏 1500

后缀数组 亚马逊笔试题最后一道题考了这道题

今天下午看完了后缀树的原理2011.10.26 ,这篇文章写得很赞:http://hi.baidu.com/bupt1/blog/item/7391c0246fdb7a1f918f9dca.html 本文转自http://hi.baidu.com/lewutian/blog/item/4d098138d29c34f9b311c725.html 单...

松篁 308
上一篇: 实用算法实现-第 8 篇 后缀树和后缀数组 [3 两个字符串的最长公共子串]
下一篇: 实用算法实现-第 9 篇 RMQ问题
存储李希
博客等级 码龄15年 418粉丝 69原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值