赞一个:
- /*
- * 已知两个字符串,String a = "abcdefghijklmnopqrstuvwxyz";String b="1234567890abcdfrgtddd12321414";
- * 编写代码求出这两个字符串中最大公共字符串
- * (最大公共字符串:比如 “abc123edf”和"bc123jg"的最大公共字符串是“bc123”)。
- * */
- public class Test06 {
- public static void main(String[] args) {
- String a = "abcdefghijklmnopqrstuvwxyz";
- String b = "1234567890abcdfrgtddd12321414";
- System.out.println(getMaxLongCommonSubstring(a, b));
- }
- /*
- * 思路:先判断两字符串的长度。判断短的是否匹配长的。
- */
- public static String getMaxLongCommonSubstring(String strA, String strB) {
- String L = null;
- String S = null;
- if (strA.length() >= strB.length()) {
- L = strA;
- S = strB;
- } else {
- L = strB;
- S = strA;
- }
- if (L.indexOf(S) >= 0) {
- return S;
- }
- String subString = null;
- int len = 0;
- String result = null;
- for (int beginIndex = 0; beginIndex < S.length() - 1; beginIndex++) {
- for (int endIndex = S.length(); endIndex > beginIndex; endIndex--) {
- subString = S.substring(beginIndex, endIndex);
- System.out.println((endIndex - beginIndex) + "==" + subString);
- if (L.indexOf(subString) >= 0) {
- if (len < (endIndex - beginIndex)) {
- len = endIndex - beginIndex;
- result = subString;
- }
- }
- }
- }
- return result;
- }
- }
复制代码 |