1. 程式人生 > >演算法題-兩個字串的最大公共子串

演算法題-兩個字串的最大公共子串

題目:給定一個query和一個text,均由小寫字母組成。要求在text中找出以同樣順序連續出現在query中最長連續字母序列的長度。例如,query為“acbac”,text為“acaccbabb”,那麼text中的“cba”為最長的連續出現在query中的字元序列,因此,返回結果應該為其長度3。請注意程式效率。

自己的程式碼

package com.larry.test;

public class Test {
	/**
	 * 兩個字串的最大公共子串
	 * @param a
	 * @param b
	 * @return
	 */
	private int maxComSubString(String a, String b){
		//保證a為較短的字串
		if(a.length() > b.length()){
			String temp = a;
			a = b;
			b = temp;
		}
		int m = 0, n = 0;
		m = a.length();
		n = b.length();
		int loc_x = 0, loc_y = 0;
		int max = 0;
		int c[][] = new int[m][n];
		for(int i = 0; i < m; i++){
			for(int j = 0; j < n; j++){
				if(i > 0 && j > 0 && a.charAt(i) == b.charAt(j)){
					c[i][j] = c[i-1][j-1] + 1;
					if(c[i][j] > max) {max = c[i][j];loc_x = i; loc_y = j;} 
				}
			}
		}
		System.out.println("loc_x = " + loc_x + " loc_y = " + loc_y);
		return max;
	}
	public static void main(String[] args) {
		String a = "acbac", b = "acaccbabb";
		System.out.println(new Test().maxComSubString(a, b));
	}
}