我正在尝试实现 2 个字符串的最长公共子序列。我的方法与这里发布的有点不同。我接近解决方案,但问题不大。请帮我。
我的问题:期望输出:metalica 电流输出:etallica
我的代码是:
import java.util.ArrayList;
import java.util.Stack;
public class CommonSubS {
public static void main(String[] args) {
ArrayList<Character> ss = new ArrayList<>();
String s1 = "metallicarules";
String s2 = "rulmetallicales";
ArrayList<ArrayList<Character>> one = new ArrayList<>();
char[] first = s1.toCharArray();
char[] second = s2.toCharArray();
int j = 0;
int current = 0;
int mainIndex = 0;
ArrayList<Character> sec = new ArrayList<>();
// search for each char in second
for(int i = 0; i<second.length; i++)
{
j = current;
// search for each char in first
while(j<first.length)
{
// if match found, add to the arraylist
if(first[j] == second[i]){
sec.add(first[j]);
current = j+1;
break;
}
else
{ // if different char occured in between,
// save current arraylist in one
// and go forward
one.add(sec);
sec = new ArrayList<>();
j++;
current = 0;
}
}
}
for(ArrayList<Character> s: one)
{
for(Character c: s)
{
System.out.print(c);
}
System.out.println();
}
}
}
/*
desired output: metallica
current output: etallica
*/
我知道还有其他方法,但我尝试使用简单的方法来实现。请指出问题。