- 上一篇文章中介紹了正向最大匹配,可以看到有時候效果不是很好,這裏在介紹一種逆向最大匹配的算法。詞典和匹配的字符串都和上一篇文章相同</span>
只是本算法是從後到前搜索字符串,然後找到最長的匹配結果輸出。上代碼
- <pre code_snippet_id="331438" snippet_file_name="blog_20140507_2_819878" name="code" class="java">package com;
- import java.util.ArrayList;
- import java.util.List;
- public class Segmentation1 {
- private List<String> dictionary = new ArrayList<String>();
- private String request = "北京大學生前來應聘";
- public void setDictionary() {
- dictionary.add("北京");
- dictionary.add("北京大學");
- dictionary.add("大學");
- dictionary.add("大學生");
- dictionary.add("生前");
- dictionary.add("前來");
- dictionary.add("應聘");
- }
- private boolean isIn(String s, List<String> list) {
- for(int i=0; i<list.size(); i++) {
- if(s.equals(list.get(i))) return true;
- }
- return false;
- }
- public String rightMax() {
- String response = "";
- String s = "";
- for(int i=request.length()-1; i>=0; i--) {
- s = request.charAt(i) + s;
- if(isIn(s, dictionary) && tailCount(s, dictionary)==1) {
- response = (s + "/") + response;
- s = "";
- } else if(tailCount(s, dictionary) > 0) {
- } else {
- response = (s + "/") + response;
- s = "";
- }
- }
- return response;
- }
- private int tailCount(String s, List<String> list) {
- int count = 0;
- for(int i=0; i<list.size(); i++) {
- if((s.length()<=list.get(i).length()) && (s.equals(list.get(i).substring(list.get(i).length()-s.length(), list.get(i).length())))) count ++;
- }
- return count;
- }
- public static void main(String[] args) {
- Segmentation1 seg = new Segmentation1();
- seg.setDictionary();
- String response2 = seg.rightMax();
- System.out.println(response2);
- }
- }
- </pre><br>
- <br>
- <pre></pre>
- <br>
- <p>可以看到運行結果是:北京/大學生/前來/應聘/</p>
- <p>分詞效果很好</p>
- <p><br>
- </p>
- 頂