Java String Distance editDistance(String s, String t)

Here you can find the source of editDistance(String s, String t)

Description

edit Distance

License

Apache License

Declaration

public static int editDistance(String s, String t) 

Method Source Code

//package com.java2s;
/**//from  w w w  .jav a 2  s  .c  o m
   * 
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at
    
http://www.apache.org/licenses/LICENSE-2.0
    
  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied.  See the License for the
  specific language governing permissions and limitations
  under the License.
   * 
   * @author Wei Zhang,  Language Technology Institute, School of Computer Science, Carnegie-Mellon University.
   * email: wei.zhang@cs.cmu.edu
   * 
   */

public class Main {
    public static int editDistance(String s, String t) {
        int m = s.length();
        int n = t.length();
        int[][] d = new int[m + 1][n + 1];
        for (int i = 0; i <= m; i++) {
            d[i][0] = i;
        }
        for (int j = 0; j <= n; j++) {
            d[0][j] = j;
        }
        for (int j = 1; j <= n; j++) {
            for (int i = 1; i <= m; i++) {
                if (s.charAt(i - 1) == t.charAt(j - 1)) {
                    d[i][j] = d[i - 1][j - 1];
                } else {
                    d[i][j] = min((d[i - 1][j] + 1), (d[i][j - 1] + 1), (d[i - 1][j - 1] + 1));
                }
            }
        }
        return (d[m][n]);
    }

    public static int min(int a, int b, int c) {
        return (Math.min(Math.min(a, b), c));
    }
}

Related

  1. editDistance(CharSequence first, CharSequence second)
  2. editDistance(String one, String two)
  3. editDistance(String s, String t)
  4. editDistance(String s, String t)
  5. editDistance(String s0, String s1)
  6. EditDistance(String s1, String s2)