Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

public class Main {
    /**
     * Longest Common String
     * 
     * e.g.
     * 
     *       wefuhLongestStringwewhe
     * 
     *       12weLongestString11
     * 
     * */

    private static int gStart = 0, gLength = 0;
    private static int calledTimes = 0;

    public static String longestCommonString(String str1, String str2) {
        if (str1 == null || str2 == null || str1.length() == 0 || str2.length() == 0)
            return null;

        char[] cc1 = str1.toCharArray();
        char[] cc2 = str2.toCharArray();

        for (int i = 0; i < cc1.length; i++) {
            for (int j = 0; j < cc2.length; j++) {
                check(cc1, cc2, i, j);
            }
        }

        StringBuilder sb = new StringBuilder();
        while (gLength > 0) {
            sb.append(cc1[gStart++]);
            gLength--;
        }

        return sb.toString();
    }

    public static void check(char[] cc1, char[] cc2, int start1, int start2) {
        int start = start1, length = 0;
        while (start2 < cc2.length && start1 < cc1.length) {
            calledTimes++;
            if (cc1[start1] == cc2[start2]) {
                start1++;
                start2++;
                length++;
            } else {
                break;
            }
        }

        if (length > gLength) {
            gStart = start;
            gLength = length;
        }

    }
}