zoukankan      html  css  js  c++  java
  • 最长公共字符串

    对于最长公共字符串问题:
    我的方法是采用动态规划求解,所有格子默认为0,当字符相同时就在对应的格子填入其左上角数字加1的结果。然后格子中的最大值即最大公共字符串的长度。
    这里写图片描述

    #include<iostream>
    #include<cstring>
    #include<vector>
    using namespace std;
    //str1为横向,str2这纵向
    const string LCS(const string& str1, const string& str2){
        int x = str1.length();
        int y = str2.length();
        int data[100][100] = {0};
    
        int pos = -1;
        int max = 0;
        for(int i = 0; i < x; i ++)
        {
            for(int j = 0; j < y; j ++)
            {
                if(str2[j] == str1[i])
                {
                    //左上角数字加1
                    data[i+1][j+1] = data[i][j] + 1;
                    if(data[i+1][j+1] > max)
                    {
                        max = data[i+1][j+1];
                        pos = j;
                    } 
                }   
            }
        }
        ///获取最长公共字符串
        string res = str2.substr(pos - max + 1 ,max);
        return res;
    }
    int main(){
        string str1("helloworldandc");
        string str2("world");
        string lcs = LCS(str1, str2);
        cout << lcs << endl;
        return 0;
    }
  • 相关阅读:
    P1012拼数
    P1622释放囚犯
    P1064 金明的预算方案
    P1754球迷购票问题
    卡塔兰数
    P1474货币系统
    P2562kitty猫基因
    P3984高兴的津津
    5-servlet简介
    java通过百度AI开发平台提取身份证图片中的文字信息
  • 原文地址:https://www.cnblogs.com/topk/p/6580106.html
Copyright © 2011-2022 走看看