我正在尝试解决任意给定两个字符串的ASCII距离问题。我已经编写了代码来检查两个字符串之间是否存在不匹配的字符,并计算了部分ascii距离。但是我仍然需要比较两个字符串(例如,如下所示),并提出可以从这些字符串中构建的通用字符串。这是下面的示例。
Let's say s1="elete" s2="leet"
Expected Output:
"let"
在上述示例中,如何识别两个字符串中的多余字符并提出一个通用字符串?
我的代码如下所示,它的作用是比较两个字符串并计算两个字符串之间不匹配字符的ASCII分数。
代码:
class Solution {
public int minimumDeleteSum(String s1, String s2) {
int sum = 0;
char[] cstr1 = s1.toCharArray();
char[] cstr2 = s2.toCharArray();
String res = compareCharacters( cstr1,cstr2 );
sum += Integer.parseInt( res.split(",")[1] );
String news1 = res.split(",")[0];
res = compareCharacters( cstr2,cstr1 );
sum += Integer.parseInt( res.split(",")[1] );
String news2 = res.split(",")[0];
/*Would like to add the code here to get all characters that are not allowing to build a common string and get their ASCII values.How do I approach this problem? */
return sum;
}
public String compareCharacters( char[] cstr1, char[] cstr2 ){
int ascii_score = 0;
int flag = 0;
StringBuilder sb = new StringBuilder();
for( int i=0;i<cstr1.length;i++ ){
flag = 0;
for( int j=0;j<cstr2.length;j++ ){
if( cstr1[i] == cstr2[j] )
flag++;
}
if( flag == 0 ){
ascii_score += (int)cstr1[i];
cstr1[i] = '\0';
}
if( flag>0 )
sb.append(cstr1[i]);
}
return sb.toString()+','+Integer.toString(ascii_score);
}
}
如有任何疑问,请通知我。在此先感谢!
答案 0 :(得分:-1)
与https://stackoverflow.com/a/51334221/1139196重复。我对代码进行了些微修改,以适应您的问题。
import java.util.Arrays;
import java.util.List;
public class LongestCommonSubstring {
public static char[] lcs(List l1, List l2) {
int[][] d = new int[l1.size() + 1][l2.size() + 1];
for (int i1 = 1; i1 <= l1.size(); i1++) {
for (int i2 = 1; i2 <= l2.size(); i2++) {
if (l1.get(i1 - 1).equals(l2.get(i2 - 1))) {
d[i1][i2] = d[i1 - 1][i2 - 1] + 1;
} else {
d[i1][i2] = Math.max(d[i1 - 1][i2], d[i1][i2 - 1]);
}
}
}
int i1 = l1.size(), i2 = l2.size();
char[] result = new char[d[i1][i2]];
while (i1 > 0 && i2 > 0) {
if (l1.get(i1 - 1).equals(l2.get(i2 - 1))) {
result[d[i1][i2] - 1] = ((String) l1.get(i1 - 1)).charAt(0);
i1 -= 1;
i2 -= 1;
} else if (d[i1][i2] == d[i1 - 1][i2]) {
i1 -= 1;
} else {
i2 -= 1;
}
}
return result;
}
public static void main(String[] args) {
List l1 = Arrays.asList("elete".split(""));
List l2 = Arrays.asList("leet".split(""));
System.out.println(new String(lcs(l1, l2)));
}
}