`
gaojingsong
  • 浏览: 1152867 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

【纠错算法之单词拼写错误场景】

阅读更多

/**

 * http://gaojingsong.iteye.com/

 * @author gaojingsong

 * 单词拼写错误的几种基本场景:

 * 例如 father

 * 1、fther   漏掉字母           -->补救措施:插入字母

 * 2、faather 多写一个字母 -->补救措施:删除字母

 * 3、ftaher  字母写反          -->补救措施:交换字母

 * 4、fcther  字母写错          -->补救措施:替换字母

 */

参考代码如下

package cn.com.test.mathoutDemo;

import java.util.HashSet;
import java.util.Set;
/**
 * http://gaojingsong.iteye.com/
 * @author gaojingsong
 * 单词拼写错误的几种基本场景:
 * 例如 father
 * 1、fther   漏掉字母           -->补救措施:插入字母
 * 2、faather 多写一个字母 -->补救措施:删除字母
 * 3、ftaher  字母写反          -->补救措施:交换字母
 * 4、fcther  字母写错          -->补救措施:替换字母
 */
public class SpellCorrect {

    private static String alphabet = "abcdefghijklmnopqrstuvwxyz";

    public static Set edit(String word) {
        if (word == null)
            return null;
        Set out = new HashSet();
        // delete
        for (int i=0; i<word.length(); ++i) {
            String wd = word.substring(0,i) + word.substring(i+1,word.length());
            out.add(wd);
        }
        // insert
        for (int i=0; i<=word.length(); ++i) {
            for (int j=0; j<alphabet.length(); ++j) {
                char c = alphabet.charAt(j);
                String wd = word.substring(0,i) + c + word.substring(i,word.length());
                out.add(wd);
            }
        }
        // replace
        for (int i=0; i<word.length(); ++i) {
            for (int j=0; j<alphabet.length(); ++j) {
                char c = alphabet.charAt(j);
                String wd = word.substring(0,i) + c + word.substring(i+1,word.length());
                out.add(wd);
            }
        }
        // transpose
        for (int i=1; i<word.length(); ++i) {
            char c1 = word.charAt(i-1);
            char c2 = word.charAt(i);
            String wd = word.substring(0,i-1) + c2 + c1 + word.substring(i+1,word.length());
            out.add(wd);
        }

        return out;
    }

    public static void main(String[] args) {
    	/**
    	 * http://gaojingsong.iteye.com/
    	 * @author gaojingsong
    	 * 单词拼写错误的几种基本场景:
    	 * 例如 father
    	 * 1、fther   漏掉字母           -->补救措施:插入字母
    	 * 2、faather 多写一个字母 -->补救措施:删除字母
    	 * 3、ftaher  字母写反          -->补救措施:交换字母
    	 * 4、fcther  字母写错          -->补救措施:替换字母
    	 */
        String word = "tao";
        System.out.println( edit(word) );
    }
}


 

 
  • 大小: 59.2 KB
  • 大小: 66.2 KB
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics