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

/**

 * 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) );
    }
}


 

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值