Solution method and code implementation of editing distance

Source: Internet
Author: User
Tags first string min

For the editing distance, refer to the following URL: http://www.cnblogs.com/biyeymyhjob/archive/2012/09/28/2707343.html

The editing distance is a string at least how many steps can be changed to another string, including: Delete, add, modify. Delete and add is reflexive, i.e. edit (i-1,j) +1 or edit (i,j-1) +1. The following add 1 is the cost of modifying and adding the operation, the modification is edit (i-1,j-1) + (0|1). The next add 0 or add 1 is to see the first string of the I-character and the second string of the J-character is equal, equality is no need to modify, so add 0, not equal to the need for one-step modification, need to add 1.

The specific code is


public class Bijijuli {public

	static void Main (string[] args) {
		System.out.println (editinstance ("Ergabd", "ABC "));
	}
	
	private static int min (int a,int b) {
		return a < b a:b;
	}
	
	private static int Editinstance (string str1, String str2) {
		
		int max1 = Str1.length ();
		int max2 = Str2.length ();
		
		int[][] Matrix = new Int[max1+1][max2+1];
		
		for (int i=0;i<max1+1;i++) {
			matrix[i][0] = i;
		}
		for (int i = 0;i<max2+1;i++) {
			matrix[0][i] = i;
		}
		
		for (int i=1;i<max1+1;i++) {for
			(int j=1;j<max2+1;j++) {
				int d = 1; 
				int temp = min (matrix[i-1][j]+1,matrix[i][j-1]+1);
				if (str1.substring (i-1, i). Equals (Str2.substring (j-1,j))) {
					d = 0;
				}
				Matrix[i][j] = min (temp,matrix[i-1][j-1]+d);
			}
		}
		return MATRIX[MAX1][MAX2];
	}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.