给定一个query和一个text,均由小写字母组成。要求在text中找出以同样的顺序连续出现在query中的最长连续字母序列的长度。例如, query为“acbac”,text为“acaccbabb”,那么text中的“cba”为最长的连续出现在query中的字母序列,因此,返回结果应该为其长度3。请注意程序效率。(最长公共子序列)
package org.algorithm; public class GetPublicStr { //定义获取公共子串方法 public void getPubString(char[] text, char[] query) { int textLen = text.length;//待查文档长度 int queryLen = query.length;//待查关键词长度 int maxLen = textLen > queryLen ? textLen : queryLen; int[] max = new int[maxLen];// 保存最长子串长度的数组 int[] maxIndex = new int[maxLen];// 保存最长子串长度最大索引的数组 int[] c = new int[maxLen]; int i, j;// 临时变量 for (i = 0; i < queryLen; i++) { for (j = textLen - 1; j >= 0; j--) { if (query[i] == text[j]) { if ((i == 0) || (j == 0)) c[j] = 1; else c[j] = c[j - 1] + 1;// 此时C[j-1]还是上次循环中的值,因为还没被重新赋值 } else { c[j] = 0; } // 如果是大于那暂时只有一个是最长的,而且要把后面的清0; if (c[j] > max[0]) { max[0] = c[j]; maxIndex[0] = j; for (int k = 1; k < maxLen; k++) { max[k] = 0; maxIndex[k] = 0; } } // 有多个是相同长度的子串 else if (c[j] == max[0]) { for (int k = 1; k < maxLen; k++) { if (max[k] == 0) { max[k] = c[j]; maxIndex[k] = j; break; // 在后面加一个就要退出循环了 } } } } for (int temp : c) { System.out.print(temp); } System.out.println(); } // 打印最长子字符串 for (j = 0; j < maxLen; j++) { if (max[j] > 0) { System.out.println("第" + (j + 1) + "个公共子串:"); int k = 0; for (i = maxIndex[j] - max[j] + 1; i <= maxIndex[j]; i++) { k++; System.out.print(text[i]); } System.out.println("公共子串长度:" + k); } } } //程序入口方法 public static void main(String[] args) { GetPublicStr getPubStr = new GetPublicStr(); String text = new String("acaccbabb");// 待查文档 String query = new String("acbac");// 待查关键词 getPubStr.getPubString(text.toCharArray(), query.toCharArray());// 求连续公共子串方法 } }