"Huawei OJ" "Algorithm Total chapter" "Huawei OJ" "083-Calculate the similarity of Strings" "Project Download" topic description
对于不同的字符串,我们希望能有办法判断相似程度,我们定义了一套操作方法来把两个不相同的字符串变得相同,具体的操作方法如下:1 修改一个字符,如把“a”替换为“b”。2 增加一个字符,如把“abdd”变为“aebdd”。3 删除一个字符,如把“travelling”变为“traveling”。比如,对于“abcdefg”和“abcdef”两个字符串来说,我们认为可以通过增加和减少一个“g”的方式来达到目的。上面的两种方案,都只需要一次操作。把这个操作所需要的次数定义为两个字符串的距离,而相似度等于“距离+1”的倒数。也就是说,“abcdefg”和“abcdef”的距离为1,相似度为1/2=0.5.给定任意两个字符串,你是否能写出一个算法来计算出它们的相似度呢?请实现如下接口/** * 功能:计算字符串的相似度 * 输入:pucAExpression/ pucBExpression:字符串格式,如: "abcdef" * 返回:字符串的相似度,相似度等于“距离+1”的倒数,结果请用1/字符串的形式,如1/2 */public static String stringDistance(String expressionA, String expressionB) { /* 请实现*/ return null;}约束: 1、PucAExpression/ PucBExpression字符串中的有效字符包括26个小写字母。 2、PucAExpression/ PucBExpression算术表达式的有效性由调用者保证; 3、超过result范围导致信息无法正确表达的,返回null。
Enter a description
输入两个字符串
Output description
输出相似度,string类型
Input example
abcdefabcdefg
Output example
1/2
Algorithm implementation
ImportJava.util.Scanner;/** * Author: Wang Junshu * date:2016-01-04 09:31 * declaration:all rights Reserved!!! */ Public class Main { Public Static void Main(string[] args) {Scanner Scanner =NewScanner (system.in);//Scanner Scanner = new Scanner (Main.class.getClassLoader (). getResourceAsStream ("Data.txt")); while(Scanner.hasnext ()) {String a = Scanner.nextline (); String B = scanner.nextline (); System.out.println ("1/"+ (Stringdistance (A.tochararray (), B.tochararray ()) +1)); } scanner.close (); }/** * is a classic topic that can be solved using dynamic programming methods, and is similar to the longest common subsequence of two strings. * <p> * Set AI as the first I character of string a (A1A2A3 ... am) * Set BJ as the first J character of String B (B1b2b3 ... bn) (that is, b1,b2,b3 ... bj) * &L T;p> * Sets L (I,J) to the minimum number of operations that make two strings equal to AI and BJ. * When AI==BJ obviously l (i,j) = L (i-1,j-1) * When AI!=BJ * <p> * If they are modified to be equal, then at least two strings must also operate L (i-1,j-1) times * If you delete ai or after BJ Add Ai, then at least two strings to operate L (I-1,J) * If you delete bj or add BJ after AI, then at least two strings must also operate L (I,J-1) * At this time L (i,j) = min (L (i-1,j-1), L (i-1,j), L (i,j- 1) + 1 * <p> * Obviously, L (i,0) =i,l (0,j) =j, and then using the recursive formula above, can directly calculate the L (i,j) value. * </pre> * * @param A * @param b * @return * * Private Static int stringdistance(Char[] A,Char[] b) {int[] len =New int[A.length +1][b.length +1]; for(inti =0; i < len.length; i++) {len[i][0] = i; } for(intj =0; J < len[0].length; J + +) {len[0][J] = j; } for(inti =1; i < len.length; i++) { for(intj =1; J < len[0].length; J + +) {if(A[i-1] = = B[j-1]) {Len[i][j] = len[i-1][j-1]; }Else{Len[i][j] = Math.min (Math.min (Len[i-1][J], Len[i-1][j-1]), Len[i][j-1]) +1; } } }returnLen[len.length-1][len[0].length-1]; }}
"Huawei OJ" "083-calculates the similarity of strings"