字符串的距离

来源:互联网 发布:日耳曼狂战士 知乎 编辑:程序博客网 时间:2024/05/22 08:00

Problem
设有字符串X,我们称在X的头尾及中间插入任意多个空格后构成的新字符串为X的扩展串,如字符串X为“abcbcd”,则字符串“abcb□cd”,“□a□bcbcd□”和“abcb□cd□”都是X的扩展串,这里“□”代表空格字符。 如果A1是字符串A的扩展串,B1是字符串B的扩展串,A1与B1具有相同的长度,那么我们定义字符串A1与B1的距离为相应位置上的字符的距离总和,而两个非空格字符的距离定义为它们的ASCII码的差的绝对值,而空格字符与其它任意字符之间的距离为已知的定值K,空格字符与空格字符的距离为O。在字符串A、B的所有扩展串中,必定存在两个等长的扩展串A1、B1,使得A1与B1之间的距离达到最小,我们将这一距离定义为字符串A、B的距离。 请你写一个程序,求出字符串A、B的距离。

Input
有多组数据,每一组数据第一行为字符串A,第二行为字符串B,A、B均由小写字母组成且长度均不超过2000,第三行为一个整数K,1≤K≤100,表示空格与其它字符的距离。

Output
每组数据一行包含一个整数,表示要求的字符串A、B的距离。

Sample Input
cmc
snmn
2

Sample Output
10

 

package common.test;import java.util.ArrayList;import java.util.List;import java.util.Scanner;public class test_1 {static List<String> list1 = new ArrayList<String>();static List<String> list2 = new ArrayList<String>();public static void play(int n, String tempStr, String str, int limit,List<String> list) {if (n == str.length()) {list.add(tempStr.substring(0, tempStr.length() - 1));return;}for (int i = 0; i <= limit; i++) {String startStr = str.charAt(n) + "";String temp = "";for (int j = 0; j < i; j++)temp += "*";tempStr = tempStr + temp + startStr;play(n + 1, tempStr, str, limit, list);tempStr = tempStr.substring(0,(tempStr.length() - (temp.length() + startStr.length())));}}public static int CalcResult(String str1, String str2, int k) {int sum = 0;for (int i = 0; i < str1.length(); i++) {char value1 = str1.charAt(i);char value2 = str2.charAt(i);if ((value1 == '*' && value2 != '*')|| (value1 != '*' && value2 == '*'))sum += k;if (value1 != '*' && value2 != '*')sum += Math.abs(value1 - value2);}return sum;}public static void main(String[] args) {Scanner input = new Scanner(System.in);String str1 = input.next();String str2 = input.next();int k = input.nextInt();int resultValue = 4000;play(0, "", str1 + "0", str2.length(), list1);// "0"只是末尾做个标识,最后还是删除play(0, "", str2 + "0",str1.length(), list2);for (int i = 0; i < list1.size(); i++) {for (int j = 0; j < list2.size(); j++) {String compStr1 = list1.get(i);String compStr2 = list2.get(j);if (compStr1.length() == compStr2.length()) {int result = CalcResult(compStr1, compStr2, k);if (resultValue > result)resultValue = result;}}}System.out.println(resultValue);}}




上面的代码虽不太长,但是很低效,字符串长度超过5以上就有肯能堆栈溢出了,竟然抛出异常了,不过算法思想对的,但是这题用这种方法做,似乎是不恰当的,也是不可取的,所以我们得思考用别的方法解决这题了,想啊想,这样我们很快想到用动态规划,是不是能解决这个问题,而且效率会有所提高?

原创粉丝点击