我希望学习一种方法来获取两个字符串不同的部分。
假设我有这两个字符串:
String s1 = "x4.printString(\"Bianca.()\").y1();";
String s2 = "sb.printString(\"Bianca.()\").length();";
我希望从一个方法接收s1和s2作为参数,并输出如下内容:
["x4", "y1", "sb", "length"]
。我在其他帖子中寻找过类似的方法,但只找到了指向StringUtils.difference(String first, String second)的链接。但是这个方法返回第二个字符串与第一个字符串开始不同的位置。我真的不知道从哪里开始,任何建议都将不胜感激。
更新: 根据@aUserHimself的建议,我设法获得两个字符串的所有公共子序列,但这些子序列像一个唯一的字符串一样出现。
这是我的代码:
private static int[][] lcs(String s, String t) {
int m, n;
m = s.length();
n = t.length();
int[][] table = new int[m+1][n+1];
for (int i=0; i < m+1; i++)
for (int j=0; j<n+1; j++)
table[i][j] = 0;
for (int i = 1; i < m+1; i++)
for (int j = 1; j < n+1; j++)
if (s.charAt(i-1) == t.charAt(j-1))
table[i][j] = table[i-1][j-1] + 1;
else
table[i][j] = Math.max(table[i][j-1], table[i-1][j]);
return table;
}
private static List<String> backTrackAll(int[][]table, String s, String t, int m, int n){
List<String> result = new ArrayList<>();
if (m == 0 || n == 0) {
result.add("");
return result;
}
else
if (s.charAt(m-1) == t.charAt(n-1)) {
for (String sub : backTrackAll(table, s, t, m - 1, n - 1))
result.add(sub + s.charAt(m - 1));
return result;
}
else {
if (table[m][n - 1] >= table[m - 1][n])
result.addAll(backTrackAll(table, s, t, m, n - 1));
else
result.addAll(backTrackAll(table, s, t, m - 1, n));
return result;
}
}
private List<String> getAllSubsequences(String s, String t){
return backTrackAll(lcs(s, t), s, t, s.length(), t.length());
}
调用
getAllSubsequences
函数来处理这两个字符串:String s1 = "while (x1 < 5)"
String s2 = "while (j < 5)"
我收到的字符串是
["while ( < 5)"]
,而不是["while (", " < 5)"]
,我希望得到后者。我不明白我的错误在哪里。
x4
是第一个不同的字符串部分,然后.printString("Bianca.()").
是相同的,因此将被跳过,接着y1
再次不同,而();
再次相同并被跳过 - 对于第一个String
。然后对于第二个String
,sb
不同,而length
则不同。 - aUserHimself