zoukankan      html  css  js  c++  java
  • 最大公共字串LCS问题(阿里巴巴)

    给定两个串,均由最小字母组成。求这两个串的最大公共字串LCS(Longest Common Substring)。

    使用动态规划解决。

    #include <iostream>
    #include <vector>
    #include <cstring>
    #include <algorithm>
    
    using namespace std;
    
    #define MAX 100
    
    int LCS(string left, string right){
    	int imax = -1;
    	int m = left.size();
    	int n = right.size();
    
    	int i,j;
    	int x,y;
    
    	vector<vector<int> > temp(m, vector<int>(n,0));
    
    	for(i=0; i<m; i++){
    		for(j=0; j<n; j++){
    			if(left[i] == right[j]){
    				if (i == 0 || j == 0){
    					temp[i][j] = 1;
    				}else{
    					temp[i][j] = temp[i-1][j-1] + 1;
    				}
    
    				if(temp[i][j] > imax){
    					imax = temp[i][j];
    					x = i;
    					y = j;
    				}
    			}
    		}
    	}
    
    	/* output the common substring */
    	i = x, j = y;
    	int k = imax;
    	string s(min(m,n),0);
    	s[k--] = '';
    
    	while(i>=0 && j>=0){
    		if(left[i] == right[j]){
    			s[k--] = left[i];
    			i--;
    			j--;
    		}else{
    			break;
    		}
    	}
    	
    	cout<<s<<endl;
    
    	return imax;
    }
    
    int main(){
    	int result = 0;
    
    	string query, text;
    	cin>>query>>text;
    
    	cout<<query<<endl;
    	cout<<text<<endl;
    
    	result = LCS(query, text);
    
    	cout<<result;
    
    	return 0;
    }
    
  • 相关阅读:
    SpringMVC框架(2)
    SpringMVC框架(1)
    (数据结构与算法)跳表实现
    第2次作业
    第1次作业
    第一次作业
    第一周作业.
    第一周作业
    第0次作业
    第一次作业
  • 原文地址:https://www.cnblogs.com/fangying7/p/4722402.html
Copyright © 2011-2022 走看看