pure-jcore/src/main/java/leetcode/LongestCommonSubstring.java
/**
     * This is way 1 of using brute force approach to solve the problem.
     * Time complexity: O(n^3).
     * Space complexity: O(n).
     */
This is way 1 of using brute force approach to solve the problem.
This is way 1 of using brute force approach to solve the problem .
private String way1(String s1, String s2) {
        int len1 = s1.length(), len2 = s2.length();
        int commonStrStart = -1, commonStrEnd = -1, commonStrLen = -1;
        String commonStr = "";
        for (int i = 0; i < len1; i++) {
            for (int j = 0; j < len2; j++) {
                char c1 = s1.charAt(i);
                char c2 = s2.charAt(j);
                if (c1 == c2) {
                    int ind1 = i, ind2 = j; 
                    while (c1 == c2) {
                        if (ind1 == i) {
                            commonStrStart = commonStrEnd = i;
                        } else {
                            commonStrEnd += 1; 
                        }
                        if (++ind1 >= len1 || ++ind2 >= len2) {
                            break;
                        }
                        c1 = s1.charAt(ind1);
                        c2 = s2.charAt(ind2);
                    }
                    if (commonStrEnd - commonStrStart + 1 > commonStr.length()) {
                        commonStr = s1.substring(commonStrStart, commonStrEnd + 1);
                    }
                    commonStrStart = commonStrEnd = -1;
                }
            }
        }
        return commonStr;
    }
private String way1 ( String s1 , String s2 ) { int len1 = s1 . length ( ) , len2 = s2 . length ( ) ; int commonStrStart = - 1 , commonStrEnd = - 1 , commonStrLen = - 1 ; String commonStr = "" ; for ( int i = 0 ; i < len1 ; i ++ ) { for ( int j = 0 ; j < len2 ; j ++ ) { char c1 = s1 . charAt ( i ) ; char c2 = s2 . charAt ( j ) ; if ( c1 == c2 ) { int ind1 = i , ind2 = j ; while ( c1 == c2 ) { if ( ind1 == i ) { commonStrStart = commonStrEnd = i ; } else { commonStrEnd += 1 ; } if ( ++ ind1 >= len1 || ++ ind2 >= len2 ) { break ; } c1 = s1 . charAt ( ind1 ) ; c2 = s2 . charAt ( ind2 ) ; } if ( commonStrEnd - commonStrStart + 1 > commonStr . length ( ) ) { commonStr = s1 . substring ( commonStrStart , commonStrEnd + 1 ) ; } commonStrStart = commonStrEnd = - 1 ; } } } return commonStr ; }
This is way 1 of using brute force approach to solve the problem.
This is way 1 of using brute force approach to solve the problem .
// nested loops to find the subject // if chars are equal, then go to find the substring // comparison starts from next chars // key // when ind1 >= len1 or ind2 >= len2 or c1 != c2 // save the longer substring and reset indicators