Very simple algorithm to calc the difference between 2 words. - Java java.lang

Java examples for java.lang:String Algorithm

Description

Very simple algorithm to calc the difference between 2 words.

Demo Code

/*/*  w w w.  j a  v  a2 s  .com*/
 *  JOrtho
 *
 *  Copyright (C) 2005-2009 by i-net software
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License as 
 *  published by the Free Software Foundation; either version 2 of the
 *  License, or (at your option) any later version. 
 *
 *  This program is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 *  USA.
 *  
 * Created on 16.06.2009
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String word1 = "java2s.com";
        String word2 = "java2s.com";
        System.out.println(calcDiff(word1, word2));
    }

    /**
     * Very simple algorithm to calc the diff between 2 words.
     */
    public static int calcDiff(String word1, String word2) {
        int diff = 0;
        int j = 0;
        for (int i = 0; i < word1.length(); i++) {
            char ch1 = word1.charAt(i);
            if (word2.length() <= j) {
                diff++;
                continue;
            }
            char ch2 = word2.charAt(j++);
            if (ch1 == ch2) {
                continue;
            }
            diff++;
            if (word2.length() > j && word2.charAt(j) == ch1) {
                j++;
                continue;
            }
            if (word1.length() > (i + 1) && word1.charAt(i + 1) == ch2) {
                i++;
                continue;
            }
        }
        diff += word2.length() - j;
        return diff;
    }
}

Related Tutorials