2023华为OD机试真题-查找重复代码(JAVA、Python、C++)

题目描述:

小明负责维护项目下的代码,需要查找出重复代码,用以支撑后续的代码优化,请你帮助小明找出重复的代码,。

重复代码查找方法:以字符串形式给定两行代码(字符串长度 1 < length <= 100,由英文字母、数字和空格组成),找出两行代码中的最长公共子串。

注: 如果不存在公共子串,返回空字符串

输入描述:

输入的参数text1, text2分别表示两行代码

输出描述:

输出任一最长公共子串

补充说明:

 收起

示例1

输入:

hello123world
hello123abc4
输出:

hello123
说明:

text1 = "hello123world", text2 = "hello123abc4", 最长的公共子串为 "hello123"

示例2

输入:

private_void_method
public_void_method
输出:

_void_method
说明:

text1 = "private_void_method", text2 = "public_void_method", 最长的公共子串为 "_void_method"

示例3

输入:

hiworld
hiweb
输出:

hiw
说明:

text1 = "hiworld", text2 = "hiweb", 最长的公共子串为 "hiw"
 

text1, text2 = input().strip(), input().strip()
if len(text1) > len(text2): text1, text2 = text2, text1
 
head, tail = 0, 0
flag = 0
res = ''
while tail < len(text1):
    if text1[head:tail+1] in text2:
        if tail-head+1 > flag:
            flag = tail-head+1
            res = text1[head:tail+1]
        tail += 1
    else:
        head += 1
        tail = head
print(res)
#include <bits/stdc++.h>
 
using namespace std;
 
int main() {
    string str1, str2;
    cin >> str1 >> str2;
    int len1 = str1.size();
    int len2 = str2.size();
    int ma = 0;
    string ans;
     
    vector<vector<int>> dp(len1 + 1, vector<int> (len2 + 1, 0));
    for (int i = 1; i <= len1; ++i) {
        for (int j = 1; j <= len2; ++j) {
            if (str1[i - 1] == str2[j - 1]) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
                if (dp[i][j] > ma) {
                    ma = dp[i][j];
                    ans = str1.substr(i - dp[i][j], dp[i][j]);
                }
            }
        }
    }
    cout << ans << endl;
    return 0;
}
import java.util.Scanner;
 
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s1 = in.nextLine();
        String s2 = in.nextLine();
        String result = "";
        for(int i=0;i<s1.length();i++){
            for(int j=i+1;j<=s1.length();j++){
                String sub = s1.substring(i,j);
                if(s2.contains(sub)){
                    if(result.length()<sub.length()){
                        result = sub;
                    }
                }
            }
        }
        System.out.print(result);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值