我想出了一种蛮力算法来查找两个给定字符串之间最长的公共子序列.看起来它的时间复杂度为O(n ^ 3).它通过了我所有的测试用例,但是我仍然不确定是否通过所有测试用例…..请让我知道这是正确的蛮力算法?
public String lcs(String s1,String s2) {
int s2Start = 0;
StringBuilder result = new StringBuilder("");
StringBuilder temp = new StringBuilder("");
for(int s1Start = 0; s1Start < s1.length(); s1Start++) {
s2Start = 0; // reset
if(temp.length() > result.length()) {
result = temp;
}
temp = new StringBuilder(""); // reset
for(int i = s1Start; i < s1.length(); i++) {
char s1Char = s1.charAt(i);
for(int j = s2Start; j < s2.length(); j++) {
char s2Char = s2.charAt(j);
if(s1Char == s2Char) {
temp.append(Character.toString(s1Char));
s2Start = j + 1;
break;
}
}
}
}
if(temp.length() > result.length())
result = temp;
return result.toString();
}
如果上面的代码不正确,我希望蛮力算法返回最长的公共子序列字符串,我该如何实现???
最佳答案
原文链接:https://www.f2er.com/java/532817.html