gpt4 book ai didi

Java:如何比较两个字符串以获得它们不同的部分?

转载 作者:搜寻专家 更新时间:2023-11-01 03:17:39 26 4
gpt4 key购买 nike

我想学习一种方法来获取两个字符串不同的部分。

假设我有这两个字符串:

String s1 = "x4.printString(\"Bianca.()\").y1();";
String s2 = "sb.printString(\"Bianca.()\").length();";

我想要这个输出:["x4", "y1", "sb", "length"]来自接收方法 s1s2作为参数。

我在其他帖子中寻找过类似的东西,但我只找到了指向 StringUtils.difference(String first, String second) 的链接。 .

但是这个方法从开始不同于第一个字符串的索引处返回第二个字符串。
我真的不知道从哪里开始,任何建议将不胜感激。

更新按照@aUserHimself 的建议,我设法获得了两个字符串之间的所有公共(public)子序列,但这些子序列就像一个唯一的字符串。

这是我的代码:

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)"]因为我想获得。我不明白我哪里做错了。

最佳答案

找出两个字符串之间的最长公共(public)子序列。之后,您可以使用 indexOf 获取两个字符串之间的这个公共(public)字符串的索引,并从两个字符串中获取不常见的值。

例子:

CICROSOFK
WOCROSFGT

常用字母是

CROS

查找从 0 到 SOFT 索引和从 index+'SOFT'.lengthstr.length 的不同字符串

关于Java:如何比较两个字符串以获得它们不同的部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43092414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com