题目详情
给定一个源串和目标串,能够对源串进行如下操作:
1.在给定位置上插入一个字符
2.替换任意字符
3.删除任意字符
写一个程序,返回最小操作数,使得对源串进行这些操作后等于目标串,源串和目标串的长度都小于2000。
输入:两个字符串,一个源串,一个目标串
输出:最小操作数
代码
package com.ausky.work.pongo;
/**
* 给定一个源串和目标串,能够对源串进行如下操作: 1.在给定位置上插入一个字符 2.替换任意字符 3.删除任意字符
* 写一个程序,返回最小操作数,使得对源串进行这些操作后等于目标串,源串和目标串的长度都小于2000。
*
*
*
* 输入:两个字符串,一个源串,一个目标串
*
* 输出:最小操作数
*
* @author xn-hyao-01
*
*/
public class Ponggo_1020 {
public static void main(String[] args) {
String source = "1234567891";
String desert = "0001032432";
Ponggo_1020 pongo = new Ponggo_1020();
String[] compareResult = pongo.compareString(source, desert);
//如果一个重复的都没有的话 需要将source删除 将desert 全部重新插入
int operatorCounts = source.length() + desert.length();
for(String str : compareResult){
System.out.println(str);
}
System.out.println(compareResult);
String result = "";
for(int i = 0; i < compareResult.length;i++){
String tmpResult = pongo.recursionSource(compareResult, i, -1, "");
if(result.length() <= tmpResult.length()){
result = tmpResult;
}
}
if(result.length() >0){
operatorCounts = operatorCounts - result.length();
}
System.out.println(operatorCounts);
}
/**
* 获取比较结果
* @param source
* @param disert
* @return
*/
private String[] compareString(String source, String desert){
char[] sourceChars = source.toCharArray();
char[] desertChars = desert.toCharArray();
String[] sourceComperDesert = new String[source.length()];
int seat = 0;
for(char sourceChar : sourceChars){
StringBuilder comperRes = new StringBuilder();
for(char desertChar : desertChars){
if(sourceChar == desertChar){
comperRes.append("1");
}else{
comperRes.append("0");
}
}
sourceComperDesert[seat] = comperRes.toString();
seat++;
}
return sourceComperDesert;
}
private String recursionSource(String[] sourceComperDisert, int arraySeat,
int stringSeat, String sourceSeats) {
int arraySize = sourceComperDisert.length;
String recursionRes = sourceSeats;
for (; arraySeat < arraySize; arraySeat++) {
String source = sourceComperDisert[arraySeat];
int nextStringSeat = source.indexOf('1', stringSeat + 1);
if (nextStringSeat != -1) {
String tmpRes = recursionSource(sourceComperDisert, arraySeat + 1,
nextStringSeat, sourceSeats + arraySeat + ",");
if(recursionRes.length() < tmpRes.length()){
recursionRes = tmpRes;
}
}
}
return recursionRes;
}
}