对某个集合范围内的词组,例如公司内所有职员姓名做自动完成,例如黄海晏,输入hhy,huanghy,hhaiy,hhyan,皆能匹配到。 算法代码: /** * 不完整拼音匹配算法,可用到汉字词组的自动完成 * 拼音搜索匹配 huang hai yan => huhy,hhy * 通过递归方法实现 * * @param search 输入的拼音字母 * @param pinyin 汉字拼音数组,通过pinyin4j获取汉字拼音 @see http://pinyin4j.sourceforge.net/ * @return 匹配成功返回 true * @author 黄海晏 */ public static boolean distinguish(char[] search, int searchIndex, String pinyin[], int wordIndex, int wordStart) { if (searchIndex == 0) return search[0] == pinyin[0].charAt(0) &&//第一个必须匹配 (search.length == 1 || distinguish(search, 1, pinyin, 0, 1));//如果仅是1个字符,算匹配,否则从第二个字符开始比较 if (pinyin[wordIndex].length() > wordStart//判断不越界 && search[searchIndex] == pinyin[wordIndex].charAt(wordStart))//判断匹配 return searchIndex == search.length - 1 ? distinguish(search, pinyin, wordIndex)//如果这是最后一个字符,检查之前的声母是否依次出现 : distinguish(search, searchIndex + 1, pinyin, wordIndex, wordStart + 1);//同一个字拼音连续匹配 else if (pinyin.length > wordIndex + 1 //判断不越界 && search[searchIndex] == pinyin[wordIndex + 1].charAt(0)) //不能拼音连续匹配的情况下,看看下一个字拼音的首字母是否能匹配 return searchIndex == search.length - 1 ? distinguish(search, pinyin, wordIndex) //如果这是最后一个字符,检查之前的声母是否依次出现 : distinguish(search, searchIndex + 1, pinyin, wordIndex + 1, 1);//去判断下一个字拼音的第二个字母 else if (pinyin.length > wordIndex + 1)//回退试试看 对于zhuang an lan searchIndex > 1 && for (int i = 1; i < searchIndex; i++) if (distinguish(search, searchIndex - i, pinyin, wordIndex + 1, 0)) return true; return false; } /** * 辅佐函数,确保pinyin[n].charAt(0)(n<=wordIndex)都按顺序依次出现在search里面 * 防止zhou ming zhong匹配zz,跳过了ming * * @param search * @param pinyin * @param wordIndex 已经匹配到拼音索引 * @return 都按顺序依次出现了,返回true */ private static boolean distinguish(char[] search, String pinyin[], int wordIndex) { String searchString = new String(search); int lastIndex = 0; int i = 0; for (i = 0; i < wordIndex; i++) { lastIndex = searchString.indexOf(pinyin[i].charAt(0), lastIndex); if (lastIndex == -1) return false; lastIndex++; } return true; } //test public static void main(String[] args) { String pinyin[]={"zhuang","an","lan"}; boolean b = distinguish("zal".toCharArray(), 0,pinyin, 0, 0); System.out.println("zal = " + b); b = distinguish("zhuanganl".toCharArray(), 0,pinyin, 0, 0); System.out.println("zhuanganl = " + b); b = distinguish("zhuananl".toCharArray(), 0,pinyin, 0, 0); System.out.println("zhuananl = " + b); b = distinguish("zhuanl".toCharArray(), 0,pinyin, 0, 0); System.out.println("zhuanl = " + b); b = distinguish("zhl".toCharArray(), 0,pinyin, 0, 0); System.out.println("zhl = " + b);//false,非连续匹配,跳过了安 }