1. 程式人生 > 其它 >永無鄉

永無鄉

連結

給定兩個字串str1和str2,輸出兩個字串的最長公共子串,如果最長公共子串為空,輸出-1。

import java.util.Scanner;

public class Main {

    private static String solve(String str1, String str2) {
        int maxLenght = 0, maxIndex = 0;

        int row = 0, col = str2.length() - 1;

        while (row < str1.length() && col >= 0) {

            int dp = 0;
            int x = row, y = col;

            while (x < str1.length() && y < str2.length()) {
                dp = str1.charAt(x) == str2.charAt(y) ? dp + 1 : 0;

                if (dp > maxLenght) {
                    maxLenght = dp;
                    maxIndex = x;
                }

                x++;
                y++;
            }

            if (col > 0) {
                col--;
            } else {
                row++;
            }
        }

        return maxLenght == 0 ? "-1" : str1.substring(maxIndex - maxLenght + 1, maxIndex + 1);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            System.out.println(solve(in.next(), in.next()));
        }
    }
}
心之所向,素履以往 生如逆旅,一葦以航