华为OD题目:找出重复代码

package com.sf.ccmas.video.config.odd.od5;

import java.util.Scanner;

/**
 * 本期题目:找出重复代码
 * 题目描述
 * 小明负责维护项目下的代码,需要查找出重复代码,用以支撑后续的代码优化,请你帮助小明找出重复的代码。
 * 重复代码查找方法:以字符串形式给出两行代码(字符审长度1< length < 100,由英文字母、数字和空格组成),找出两行代码中的最长公共子串
 * 注:如果不存在公共子串,返回空字符串
 * 输入描述
 * 输入的参数 text1,text2 分别表示两行代码
 * 输出描述
 * 输出任一最长公共子串
 * 示例一
 * 输入
 * hello123world1
 * hello123abc4
 * 输出
 * hello123
 *
 * 示例二
 * 输入
 * a_private_void_method
 * public_void_method
 *
 */

public class Search {
    //解题方法:双指针法, 题目要求返回下标最大的字串,可以用倒序遍历字符串,返回第一个结果
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String strOne = sc.nextLine();
        String strTwo = sc.nextLine();
        int lengthOne = strOne.length();
        int lengthTwo = strTwo.length();
        String moreStr = lengthOne >= lengthTwo ? strOne : strTwo;
        String lessStr = lengthOne < lengthTwo ? strOne : strTwo;
        int minLength = lessStr.length();
        String maxSubstring = null;
        //子串的最大长度
        int maxLen = 0;
        for (int i = 0; i < lessStr.length(); i++) {
            for (int j = i+1; j < lessStr.length(); j++) {
                String substring = lessStr.substring(i, j);
                if (moreStr.contains(substring)) {
                    if (substring.length() > maxLen) {
                        maxSubstring = substring;
                        maxLen = substring.length();
                    }
                }
            }

        }
        System.out.println(maxSubstring);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值