这里可以避免递归吗?这里的 Java 代码处理两个字符串。找到可以将一个字符串转换为另一个字符串的最少方法。一次我们可以从字符串中删除字符、添加字符或替换字符。
公共类MinimumWays {
public static int colorSequences(String input1,String input2)
{
return new MinimumWays().transform(input1, input2);
}
public int transform(String inp1, String inp2){
int a = 0; int b=0; int c=0; int result =0;
if(inp1.length()==0){
result = inp2.length();
return result;
}
else if(inp2.length()==0){
result =inp1.length();
return result;
}
if(inp1.substring(0, inp1.length()-1).equals(inp2)||inp1.substring(1, inp1.length()).equals(inp2)){
a=0;
return a;
}
else{
a = Math.min(transform(inp1.substring(0, inp1.length()-1), inp2), transform(inp1.substring(1, inp1.length()), inp2) );
}
if(inp2.substring(0, inp2.length()-1).equals(inp1)||inp2.substring(1,inp2.length()).equals(inp1)){
b=0;
return b;
}
else{
b = Math.min(transform(inp2.substring(0, inp2.length()-1), inp1),transform(inp2.substring(1,inp2.length()), inp1));
}
if(inp2.substring(0, inp2.length()-1).equals(inp1.substring(0, inp1.length()-1))||
inp2.substring(0, inp2.length()-1).equals(inp1.substring(1, inp1.length())) ||
inp2.substring(1, inp2.length()).equals(inp1.substring(0, inp1.length()-1)) ||
inp2.substring(1, inp2.length()).equals(inp1.substring(1, inp1.length()))){
c=0;
return c;
}
else{
int c1 = transform(inp2.substring(0, inp2.length()-1), inp1.substring(0, inp1.length()-1));
int c2 = transform(inp2.substring(1, inp2.length()), inp1.substring(0, inp1.length()-1));
int c3 = transform(inp2.substring(0, inp2.length()-1), inp1.substring(1, inp1.length()));
int c4 = transform(inp2.substring(1, inp2.length()), inp1.substring(1, inp1.length()));
c = Math.min(Math.min(c1, c2), Math.min(c3, c4));
}
result = 1+Math.min(a, Math.min(c, b));
return result;
}
public static void main(String[] args) {
String input1 = "sakdh";
String input2 = "akh";
System.out.println("Minimum Ways: " + colorSequences(input1, input2));
}
}
虽然功能上很好,但对于大字符串(即使是 6-7 个字符),它需要很多时间。我无法找出任何其他编码方式。:-(