之前一直想做個通訊錄程序,和音樂快速搜索程序,需要使用到漢字注音,還有字符串快速匹配。
可一直沒有找到高效率的算法,普通的字符串匹配算法速度太慢,如何才能在最短的時間內匹配出需要的字符串,這個問題困惑了幾個星期,今天把字符串匹配算法共享出來,具體效果跟QQ通訊錄查找聯系人的時候差不多
測試:
測試字符串: string[] pinyin = {"chen", "neng", "guang"}
測試Key: "chng" "chnengguang" "cheng" "chenengua"
基本思想:
從Key的第一個字符開始,在字符串數組的第一個pinyin[0] 開始匹配
1、當遇到追尾(字符串尾) 或 不匹配時
跳到下一個拼音(如:pinyin[1])開始匹配
1、不匹配時:
使測試Key回退一個字符再進行匹配,匹配不完成,則繼續回退,若回到第一個字符還是不匹配,則返回false
2、匹配時:
繼續往下匹配
2、繼續匹配
圖解:
代碼(C#)
public static bool PinyinMatch(string search, string[] pinyin) { int wordIndex = 0; int wordStart = 0; int searchIndex = 0; int pinyinLen = pinyin.Length; while (searchIndex < search.Length && wordIndex < pinyinLen) { //不追尾,判斷是否匹配 if (wordStart < pinyin[wordIndex].Length && search[searchIndex] == pinyin[wordIndex][wordStart]) { searchIndex++; wordStart++; } //追尾或匹配失敗 else { //到最后一個拼音,無法匹配 if (wordIndex == pinyinLen - 1) { return false; } wordIndex++; wordStart = 0; //判斷是否匹配 if (search[searchIndex] == pinyin[wordIndex][wordStart]) { searchIndex++; wordStart++; } //不匹配,回退 //補充(未完成):回退到最左邊一個字符,pinyins可以向后跳一位 else { if (searchIndex > 0) { searchIndex--; //判斷是否匹配 while (searchIndex >= 0 && search[searchIndex] != pinyin[wordIndex][0]) { searchIndex--; } if (searchIndex < 0) { searchIndex = 0; wordIndex++; wordStart = 0; } else { searchIndex++; wordStart++; } } } } } if (searchIndex == search.Length) { return true; } return false; }