字符串的最大子串问题

根据字符串找到其最大的字符子串 已知字符串比较大小的规则: a < ab; a < b; aba < ad; 给定字符串“dbdca”,请找出其最大的字符子串。 分析:对于字符串"dbdca",其子串可以是db, bdc, dca, ddc,要求最大的字符子串: 首先需要找到最大的字符,记录该字符串的位置; 从该位置之后的字符中找到最大的字符,加到步骤1中所求字符的后面; 重复步骤2,直到遍历至字符串的尾部。 这样的思路,是较为简单的。 int findMax(string str, int currPos) { 阅读详情

基于字符串的最大子串问题是经常面试的问题,想要表现的好不但要会基础的方法,同时还要学会优化的算法。

常考的有两个问题:

1:两个字符串的最大公共子串(还可能是子序列)

2:同一个字符串中相同的最大子串问题

例如输入qweabcuwabcfw,输出结果为:重复字符串的长度3和位置4

一:求两个字符串的最大公共子串


#include<iostream>
#include<string.h>
#include<vector>
using namespace std;
char out[50];
vector<string> re;

int longestSubstring1(string x, string y,int &start) {
    int xlen = x.size();
    int ylen = y.size();
    if (xlen == 0 || ylen == 0) {
        return 0;   
    }
    int max = -1;
    //暴力破解法,两重for循环加 while
    for (int i = 0; i < xlen; i++) {
        for (int j = 0; j < ylen; j++) {
            int m = i, n = j;
            int len = 0;
            while (m < xlen && n < ylen) {
                if (x[m] != y[n]) {
                    break;
                }
                m++;
                n++;
                len++;
            }
            if (len > max) {
                max = len;
                start = i;
            }
        }
    }
    return max;
}
//动态规划
int longestSubstring2(string x, string y,int &start) {
   //设置dp数组
   vector<vector<int> > f(x.size() + 1, vector<int>(y.size() + 1, 0));
   //vector< vector<int> > f;
   int max = -1;
   for (int i = 1; i <= x.size(); i++) {
       for (int j = 1; j <= y.size(); j++) {
           if (x[i - 1] != y[j - 1]) f[i][j] = 0;
           else if (x[i - 1] == y[j - 1]) f[i][j] = f[i - 1][j - 1] + 1;
           if (max < f[i][j]) {
             max = f[i][j];
             start = i;
           }
       }
    }
    return max;
}


int main()
{
    string x = "adbccadbxadebbca";
    string y = "bcadrbxad";
    int start;
    int out =longestSubstring1 (x,y,start);
    cout << out << "-" << start << endl;
    for (int i=0; i<out ;++i)
    cout << x[start + i];
    cout << endl;
    
    cout << longestSubstring2(x,y,start) <<"-" << start;
    
return 0;

}

2:c语言的写法

#include<iostream>
#include<string.h>
#include<vector>
using namespace std;
char out[50];
vector<int> myvector;
int fun(char* a , char *b)
 {
  int len_a = strlen(a);
  int len_b = strlen(b);
    if(len_a<=0||len_b<=0)
        return -1;
    char * c , *d;
    if(len_a<len_b)
    {
     c = b;
     d = a;
    }
     else
     {
         c =a ;
         d =b;
     }
    int max =0; 
  for( ; *c!='\0';c++ )
  {
      int n = 0; //n是个遍历指针,判断首字母是否相等
      for( ;*(d+n)!='\0'; ++n)
      {
       if(*c !=*(d+n))
       {
        continue;
       }
       else
       {
           int len =0;
           while(*(c+len)!='\0'&&*(c+len)==*(d+n+len)&&*(d+n+len)!='\0')
           {
           len++;
           }
           if(len>max)
           {
              max =len;
           {
                   for( int m=0;m <max;m++)  
                    {  
                        out[m]=*(c+m);  
                    }  
                    out[max]='\0';
           }
           }
    
       }
                    
      }     
       
  }
    
    return max;
 }

int main()
{
    char a[] ="adbccadbxadebbca";
    char b[]= "bcadrbxad";
    int len =fun(a,b);
    
    cout << out << endl;
    //cout << 0;
return 0;

}

还有别人的一个递归的解法,没看太懂,贴出来你们欣赏吧!

#include <iostream>
#include <string>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
//#include <windows.h>
using namespace std;


char findMaxStr(char * s1,char *s2){
    char *ss;
    static int maxlen=0;
    int len;
    if(strstr(s1,s2))  //如果S2是S1的子串
    {
        if(maxlen<strlen(s2))
        {
            maxlen=strlen(s2);
            printf("maxlen:%d result:%s\n",maxlen,s2);
        }
        return 0;
    }
    len=strlen(s2);
    if(len==1)
    {    //递归的出口函数,终止条件
        //printf("error\n");
        //return 1;
        return 1;
    }
    ss=(char *)malloc(len);
    memcpy(ss,s2,len);//内存拷贝函数
    ss[len-1]=0;
    //printf("len=%d str=%s\n",len-1,ss);
    findMaxStr(s1,ss); //是否需要注释掉??
    memcpy(ss,s2+1,len); //后移一位
    //printf("second: len=%d str=%s\n",len-1,ss);
    findMaxStr(s1,ss); //递归
    free(ss);
    return 1;
}

int main() 
{
    char a[200]="adcyioabcdefxxabcdxxx";
    char b[200]="mxx0";


    findMaxStr(a,b);
    return 0;
}

二:字符串的最长公共子串

这实质上是第一道题的变形,例如输入qweabcuwabcfw,输出结果为:重复字符串的长度3和位置4

 

第一种解法:以字符串的长度为外循环,内循环从字符串的第一个元素开始向后移动。

#include<iostream>
#include<string>
using namespace std;
int main()
{
string str, tep;
cout << "输入字符串" << endl;
cin >> str;
cout <<str.size()<<endl;
int mysize = str.size();
    int k =0;
    int max =0;
    int first;
for (int i = 1; i <mysize; i++)
{
for (int j = 0; j < mysize-i; j++)
{
    if (str[j]==str[j+i])
    {
        k++;
    }
    else
    {
        k=0;
    }
    if(k>max)
   {
     max = k;
     first =i-k+1;
    }
}
}
    cout << first << "-" << max <<endl;
return 0;

}

第二种解法

 

题目:输入一行字符串。找出当中出现的同样且长度最长的字符串,输出它及其首字符的位置。

               比如:“yyabcdabjcabceg",输出结果应该为abc 和3.

#include<iostream>
#include<string>
using namespace std;
int main()
{
string str, tep;
cout << "输入字符串" << endl;
cin >> str;
for (int i = str.length() - 1; i > 1; i--)
{
for (int j = 0; j < str.length(); j++)
{
if (j + i <= str.length())
{
size_t t = 0;
size_t num = 0;
tep = str.substr(j, i);//从大到小取子串,从j位置开始取长度为i的子串
t = str.find(tep);//正序查找
num = str.rfind(tep);//逆序查找
if (t != num)//假设两次查找位置不一致,说明存在反复子串
{
cout << tep << " " << t + 1 << endl;//输出子串及位置
system("pause");
return 0;


}
}
}
}
}
substr(j, i);//从大到小取子串,从j位置开始取长度为i的子串
t = str.find(tep);//正序查找
num = str.rfind(tep);//逆序查找
if (t != num)//假设两次查找位置不一致,说明存在反复子串
{
cout << tep << " " << t + 1 << endl;//输出子串及位置
system("pause");
return 0;


}
}
}
}
}

 

java匹配两个字符_java实现字符串匹配问题之求两个字符串的最大公共子串 转载请注明出处:http://blog.youkuaiyun.com/xiaojimanman/article/details/38924981近期在项目工作中有一个关于文本对照的需求,经过这段时间的学习,总结了这篇博客内容:求两个字符串的最大公共子串。算法思想:基于图计算两字符串的公共子串。详细算法思想參照下图:输入字符串S1:achmacmh 输入字符串S2:macham1)第a步,是将字符串s1,... 阅读详情

相关推荐

【Unity】YooAsset与HybridCLR:高效资源管理与代码热更的黄金组合

本文深入探讨了Unity开发中YooAsset与HybridCLR的组合应用,为需要长期运营的项目提供了完整的资源与代码热更新解决方案。YooAsset作为高效的资源管理框架,简化了AssetBundle的打包、加载与热更流程;而HybridCLR则攻克了IL2CPP模式下C#代码无法热更的难题。两者结合,实现了从资源到逻辑的平滑在线更新,极大提升了开发迭代与线上维护的效率。

weixin_29006701的博客 281

最大子串算法

采用Kadane算法求解最大子串和问题(线性时间复杂度情况下结题)

NEWPLAN的专栏 1万+

车联网ECU、TSP与TBOX通信流程

对比维度ECU(电子控制单元)BMS(电池管理系统)应用场景传统燃油车 + 新能源汽车仅限新能源汽车核心作用控制整车各系统运行管理动力电池安全与寿命车联网角色数据采集与传输的核心载体提供电池相关的核心数据。

tecoes的博客 1233

【C/C++刷题——leetcode】查找字符串中最大的子串

leetcode刷题,刷完这题字符串的题目,可以使你更加充分了解C语言字符串操作和C++ STL 库string类的操作

m0_62599305的博客 1784

上下文理解的AI增强方案:AI应用架构师的架构洞察

本文将从AI应用架构师的视角,深入探讨“上下文理解”的技术本质、核心挑战,以及一套可落地的上下文增强架构方案。我们会拆解上下文理解的底层需求,分析架构设计中的关键决策,并通过具体案例展示如何构建一个能“记住过去、理解现在、预测未来”的AI系统。三个维度:上下文的内容范围(短期/中期/长期)、数据类型(文本/结构化/多模态)、技术挑战(窗口限制/信息过载/跨会话一致性);三种架构模式:分层上下文存储(热/冷数据分离)、上下文路由(按需筛选)、动态压缩(适配模型窗口);四个关键组件。

欢迎来到我的优快云空间!这里聚焦AI大模型应用实战,分享前沿技术、实战案例与开发经验。 220

安检机图像处理避坑指南:从条纹校正到物质分类,那些论文里没写的工程细节

本文深入探讨了双能X射线安检机图像处理中的关键工程实践,从条纹校正到物质分类,揭示了论文中未提及的实用技巧。针对探测器校正、物质分类模糊、伪彩色系统设计等核心问题,提供了动态参数更新、空间上下文分析和自适应色彩映射等解决方案,助力提升安检系统的准确性和鲁棒性。

weixin_30325487的博客 889

子序列和子串问题算法的全面总结

1.分清楚什么是子串,什么是子序列 看文章前首先要搞清楚什么是子序列,什么是子串;子序列是指一个字串中非连续的字串,例如:字串A:123456789 它有一个子序列a:13579(非连续) 它有一个子串b:12345(连续)。 2.有关子串问题的算法 (1)最大子串 何为最大子串,例如:最大子串是要找出由数组成的一维数组中和最大的连续子串。比如{5,-3,4,2}的最大子串就是 {5,-3...

qq_41633237的博客 1万+

宝塔面板+pbootCMS建站全流程:从服务器选购到上线优化(附常见问题排查)

本文提供了一份详尽的宝塔面板与pbootCMS建站实战指南。内容涵盖从云服务器选购、宝塔面板部署与安全加固,到pbootCMS安装、权限配置、数据库连接等核心步骤。同时深入讲解了PHP环境优化、Nginx伪静态设置、缓存开启等性能与SEO优化技巧,并附有常见问题排查与后期维护建议,帮助用户高效、稳健地完成专业网站构建。

e4f5g6h的博客 661

一段字符串寻找最大的子字符串

一段字符串寻找最大的子字符串 思路:字符串:例子:iosiosios *从第一个i开始一直加到第一个s:后遇到第二个i,此时,将ios作为一个子字符串保存下来,再寻找下一个不重复子字符串osi,以此循环,每次找到下一个子字符串前先跟前一个子字符串进行比较。如果当前子字符串长度大于前一个子字符串,则替换。循环往复,直到最后一个子字符串。 在这里插入代码片 ...

jalyy的博客 1502

Win10下Altera USB-Blaster驱动安装详解:禁用数字签名与排查指南

在嵌入式开发和FPGA调试过程中,驱动安装是工程师绕不开的环节,尤其是当操作系统对驱动签名有严格限制时,硬件往往无法被正常识别。数字签名是系统验证驱动程序来源和完整性的重要机制,Win10出于安全考虑,默认拒绝加载未经签名的驱动,这正是Altera USB-Blaster下载器在设备管理器中显示未知设备或黄色感叹号的根本原因。通过理解设备管理器的排查逻辑,掌握临时禁用驱动强制签名或开启测试模式的方法,配合正确的驱动文件路径选择与手动安装操作,即可解决Quartus无法检测到下载器的问题。这一流程同样适用于许

weixin_29164497的博客 246

利用ANSYS随机振动分析功能实现随机疲劳分析

本文介绍了ANSYS随机振动分析功能,以及利用该功能,按照Steinberg提出的基于高斯分布和Miner线性累计损伤定律的三区间法进行ANSYS随机疲劳计算的具体过程。在工程应用中,汽车、飞行器、船舶以及其它各种机械或零部件,大多是在随机载荷作用下工作,当它们承受的应力水平较高,工作达到一定时间后,经常会突然发生随机疲劳破坏,往往造成灾难性的后果。因此,预测结构或零部件的随机疲劳寿命是非常有必要的。在工程界,疲劳计算广泛采用名义应力法,即以S-N曲线为依据进行寿命估算的方法,可以直接得到总寿命。

qq_38220914的博客 7611

java实现字符串匹配问题之求两个字符串的最大公共子串

本文通过简单的事例阐述字符串对比的算法思想,并用java给予实现。该算法可以用于求两个字符串的子串、最大子串等。

小鸡慢慢的专栏 8396

Linux中Hadoop 集群搭建

零、下载Hadoop: http://archive.cloudera.com/cdh5/cdh/5/?tdsourcetag=s_pctim_aiomsg 一、集群规划: 搭建的 hadoop 集群由 3 台服务器组成,分别叫做 master,salve1 和 slave2。其中 master 作为主节点,slave1 和 slave2 作为从节点。 二、网络配置: 1.查看 3 个节点的主机名...

白墨的小白博客 3992

字符串中最大子串问题

输入一个字符串,输出其最大子串长度,即子串中任两个字符不相同 。本程序只能输入字母,空格以及逗号,并且不区分大小写,输出为第一个具有最大长度的子串以及其长度。 #includeiostream>#includestring>using namespace std;int chartoi(char c)...{    if(isalnum(c))        ...{         

SeeSeaBee的专栏 1426

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

动态规划求解两个字符串的最大公共子串问题

最大公共子串长度问题就是:求两个串的所有子串中能够匹配上的最大长度是多少。比如:"abcdkkk" 和 "baabcdadabc",可以找到的最长的公共子串是"abcd",所以最大公共子串长度为4。下面的程序是采用矩阵法进行求解的,这对串的规模不大的情况还是比较有效的解法。请分析该解法的思路,并补全划线部分缺失的代码。#include &lt;stdio.h&gt; #include &lt;st...

HowtobeaHERO的博客 2522

深度学习工具包 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")

关于如何求两个字符串的最大公共子串的问题

此方法对于长度较短的字符串效率较高: #include <stdio.h> #include <string.h> int f(char s1[],char s2[]) { int a[100][100]; int len1 = strlen(s1); int len2 = strlen(s2); int i,j; memset(a,...

Kobe_G的博客 424

求两字符串最大公共子串长度问题(104)

方法一(暴力法):利用三层循环进行逐个筛选,具体思想如下,从子串1的第i个字符开始,如果它与子串2的第j个字符相同,则证明从此位置开始公共子串开始出现,则同时加1判断后一个字符是否相同(这里隐含的将这个可能成为最大子串的起始位置保存了下来,也就是i),若后一个出现不相同了,则证明公共子串已结束,然后更新最大公共串长和最大串长的起始位置,若一开始就不相同则证明以子串1第i个位置为起始位置,子串2第j个位置开始不会出现公共子串,那么就判断子串2的下一个位置,看看他是否会和子串1的i位置出现公共子串。 还可以这.

一只向入研坑的程序猿 377

最长公共子串、最长公共子序列、最长回文子串、模式匹配、最大子序列--字符串问题整理

一.最长公共子串问题集(Longest Common Substring/LCS)     最长公共子串问题的基本表述为:     给定两个字符串,求出它们之间最长的相同子字符串的长度。     最直接的解法自然是找出两个字符串的所有子字符串进行比较看他们是否相同,然后取得相同最长的那个。对于一个长度为n的字符串,它有n(n+1)/2 个非空子串。所 以假如两个字符串的长度同为n,通

Invoker's Tower 5877

删除最大嵌套字符串的子串的优化问题

删除最大嵌套字符串的子串的优化问题 pta题库上一道简单删除子串题目: ![在这里插入代码片](https://img-blog.csdnimg.cn/20190105205520775.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3F...

qq_40761125的博客 159

字符串最大公共子序列以及最大公共子串问题

最大公共子序列 [code="java"]import java.util.Random; public class LCS { public static void main(String[] args){ //设置字符串长度 int substringLength1 = 20; int substringLength2 = ...

I'am GongQi. 205

动态规划 字符串最大公共子序列以及最大公共子串问题LCS

1、先科普下最长公共子序列 & 最长公共子串的区别: 找两个字符串的最长公共子串,这个子串要求在原字符串中是连续的。而最长公共子序列则并不要求连续。 2、最长公共子串 其实这是一个序贯决策问题,可以用动态规划来求解。我们采用一个二维矩阵来记录中间的结果。这个二维矩阵怎么构造呢?直接举个例子吧:"bab"和"caba"(当然我们现在一眼就可以看出来最长公共子串是"ba"或"

zjw123king的博客 570

用java实现串匹配问题_java实现字符串匹配问题之求最大公共子串

转载请注明出处:http://blog.youkuaiyun.com/xiaojimanman/article/details/38924981最近在项目工作中有一个关于文本对比的需求,经过这段时间的学习,总结了这篇博客内容:求两个字符串的最大公共子串。算法思想:基于图计算两字符串的公共子串。具体算法思想参照下图:输入字符串S1:achmacmh 输入字符串S2:macham1)第a步,是将字符串s1,...

weixin_30825389的博客 241

java中两个字符串匹配的个数_java实现字符串匹配问题之求两个字符串的最大公共子串...

转载请注明出处:http://blog.youkuaiyun.com/xiaojimanman/article/details/38924981 近期在项目工作中有一个关于文本对照的需求,经过这段时间的学习,总结了这篇博客内容:求两个字符串的最大公共子串. 算法思想:基于图计算两字符串的公共子串.详细算法思想參照下图: 输入字符串S1:achmacmh 输入字符串S2:macham 1)第a步,是将字符...

weixin_42392425的博客 499

最长回文子串问题:给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

题目描述 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 示例 1: 输入: "babad" 输出: "bab" 注意: "aba" 也是一个有效答案。 示例 2: 输入: "cbbd" 输出: "bb" 题目分析 其实,这道题的解法有多种,包括暴力解法、动态规划、中心扩展法等,在这里,只讲述中心扩展法,剩下的几种办法,大家可以自行百度。中心扩展法的基...

qq_29462849的博客 3127
上一篇: 数组中只出现一次的数字
下一篇: 公共子串加全排列
runner668
博客等级 码龄11年 161粉丝 137原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值