最长公共子串_LintCode

给出两个字符串,找到最长公共子串,并返回其长度。


样例

给出A=“ABCD”,B=“CBCE”,返回 2

注意

子串的字符应该连续的出现在原字符串中,这与子序列有所不同。

 public int longestCommonSubstring(String A, String B) {
        // write your code here
        String A_ = A;
		String B_ = B;
		int A_len = A.length();
		int B_len = B.length();
		if(A.length() <= B.length())
		{
			for(int i=A_len-1;i>=0;i--)
				for(int j=0;j<=A_len-1-i;j++)
				{
					int x = B.indexOf(A_);
					if(x != -1)
						break;
					else
						A_ = A.substring(j, j+i+1);
				}
			return A_.length();
		}	
		else
		{
			for(int i=B_len-1;i>=0;i--)
				for(int j=0;j<=B_len-1-i;j++)
				{
					int x = A.indexOf(B_);
					if(x != -1)
						break;
					else
						B_ = B.substring(j, j+i+1);
				}
			return B_.length();
		}
    }
}


你可能感兴趣的:(lintcode)