第14题 find longest common continuous substring

来源:互联网 发布:mac电脑excel表格下载 编辑:程序博客网 时间:2024/06/06 03:25

Write Program to find longest common contiguous intersection from 2 lists provided to the function.


Example:

 list1: abcrfghwetf

 list2: abrfghwwetxyab


Longest common intersection here is: fghwNeed Effecient Algorithm to implement this in Java or C, not using arrays.


此题是2月29号amazon招聘暑期实习生的面试题


用LCS的思想来考虑此题,只需要给LCS加一些限制条件

int longest = 0;public Set<String> getLCS(String s1, String s2){if(s1 == null || s2 == null)return null;int len1 = s1.length(), len2 = s2.length();int[][] array = new int[len1 + 1][len2 + 1];Set<String> substrings = new TreeSet<String>();for(int i = 0; i < len1; i++){for(int j = 0; j < len2; j++){if(s1.charAt(i) == s2.charAt(j)){int v = array[i][j] + 1;array[i + 1][j + 1] = v;if(v > longest){longest = v;}if( v == longest){substrings.add(s1.substring(i - v + 1, i + 1));}}}}return substrings;}


但是,这样做的时间复杂度是O(m*n)


请大家想想有没有办法能把时间复杂度降到O(n)?