Simple T9 implementation with Trie

本文介绍了一种利用Trie树数据结构实现T9键盘输入法的方法。通过建立单词字典并插入到Trie树中,可以高效地进行词汇搜索。特别地,文章展示了如何针对数字输入进行字符串映射,并使用广度优先搜索查找所有可能的匹配词汇。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package hello.test;

import java.io.*;
import java.util.LinkedList;
import java.util.Queue;

public class Trie {
	
	private final int R = 26;  // the trie branches 
	private Node root = new Node(); // the root node
	
	// the t9 mapped array which maps number to string on the typing board
	private String[] t9 = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
	
	// trie node definition
	private class Node {
		private boolean isWord;
		private Node[] next;
		
		public Node() {
			this(false);
		}
		
		public Node(boolean isWord) {
			this.isWord = isWord;
			this.next = new Node[R];
		}
	}
	
	// insert a word to the trie
	public void insert(String s) {
		Node current = root;
		
		for(int i = 0; i < s.length(); i++) {
			if(current.next[s.charAt(i) - 'a'] == null) {
				Node n = new Node();
				current.next[s.charAt(i) - 'a'] = n;
			} 
			
			current = current.next[s.charAt(i) - 'a'];
		}
		
		current.isWord = true;
	}
	
	// insert a character to some node
	public void insert(Node current, char c) {
		if(current.next[c - 'a'] == null) {
			Node node = new Node();
			current.next[c - 'a'] = node;
		}
		current = current.next[c - 'a'];
	}
	
	// search a word in the trie
	public boolean search(String s) {
		Node current = root;
		
		for(int i = 0; i < s.length(); i++) {
			if(current.next[s.charAt(i) - 'a'] == null) {
				return false;
			} 
			current = current.next[s.charAt(i) - 'a'];
		}
		
		return current.isWord == true;
	}
	
	// breadth first search for a number string use queue
	public void bfs_search(String strNum) {
		Queue<String> q = new LinkedList<String>();
		
		q.add("");
		
		for(int i = 0; i < strNum.length(); i++) {
			String keyStr = t9[strNum.charAt(i) - '0'];
			int len = q.size();
			
			while(len -- > 0) {
				String preStr = q.remove();
				for(int j = 0; j < keyStr.length(); j++) {
					String tmpStr = preStr + keyStr.charAt(j);
					//q.add(tmpStr);
					if(search(tmpStr) && tmpStr.length() == strNum.length()) {
						System.out.println(tmpStr);
					} else {
						q.add(tmpStr);
					}
				}
			}
		}
	}
	
	// delete a node
	public void delete(Node node) {
		for(int i = 0; i < R; i++) {
			if(node.next != null) {
				delete(node.next[i]);
			}
		}
		node = null;
	}
	
	// print words
	public void print(Node node) {
		if(node == null) return;
		for(int i = 0; i < R; i++) {
			if(node.next[i] != null) {
				System.out.print((char) (97 + i));
				if(node.next[i].isWord == true) {
					System.out.println();
				}
				print(node.next[i]);
			}
			
		}
	}
	
	// print words from root
	public void print() {
		print(root);
	}
	
	// convert number string to String array
	private String[] numToString(String strNum) {
		String[] strArray = new String[strNum.length()];
		for(int i = 0; i < strNum.length(); i++) {
			strArray[i] = t9[strNum.charAt(i) - '0'];
		}
		return strArray;
	}
	
	/**
	 * @param args
	 * @throws IOException 
	 * @throws Exceptions 
	 */
	public static void main(String[] args) throws IOException  {
		// TODO Auto-generated method stub
		Trie t = new Trie();
		BufferedReader bufreader = new BufferedReader(new FileReader("/home/will/myworld/workspace/HelloProject/src/hello/test/testdict.txt"));
		String line = null;
		
		while((line = bufreader.readLine()) != null) {
			t.insert(line);
		}
		
		bufreader.close();
		
		//t.print();
		
		t.bfs_search("4355");
		t.bfs_search("4332");
		t.bfs_search("43556");
	}

}



  T9 has many complex features, I just write a basic function. The dictionary can be downloaded from internet. Here I just input a few words in the testdict.txt for test.  The items are:

hell
hello
idea
next
supper

#include "sys.h" #include "delay.h" #include "usart.h" #include "led.h" #include "lcd.h" #include "key.h" #include "malloc.h" #include "sdio_sdcard.h" #include "w25qxx.h" #include "ff.h" #include "exfuns.h" #include "text.h" #include "pyinput.h" #include "touch.h" #include "string.h" #include "usmart.h" /************************************************ ALIENTEK¾«Ó¢STM32¿ª·¢°åʵÑé41 T9Æ´ÒôÊäÈë·¨ ʵÑé ¼¼ÊõÖ§³Ö£ºwww.openedv.com ÌÔ±¦µêÆÌ£ºhttp://eboard.taobao.com ¹Ø×¢Î¢ÐŹ«ÖÚÆ½Ì¨Î¢Ðźţº"ÕýµãÔ­×Ó"£¬Ãâ·Ñ»ñÈ¡STM32×ÊÁÏ¡£ ¹ãÖÝÊÐÐÇÒíµç×ӿƼ¼ÓÐÏÞ¹«Ë¾ ×÷ÕߣºÕýµãÔ­×Ó @ALIENTEK ************************************************/ //Êý×Ö±í const u8* kbd_tbl[9]={"¡û","2","3","4","5","6","7","8","9",}; //×Ö·û±í const u8* kbs_tbl[9]={"DEL","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz",}; u16 kbdxsize; //ÐéÄâ¼üÅ̰´¼ü¿í¶È u16 kbdysize; //ÐéÄâ¼üÅ̰´¼ü¸ß¶È //¼ÓÔØ¼üÅ̽çÃæ //x,y:½çÃæÆðÊ¼×ø±ê void py_load_ui(u16 x,u16 y) { u16 i; POINT_COLOR=RED; LCD_DrawRectangle(x,y,x+kbdxsize*3,y+kbdysize*3); LCD_DrawRectangle(x+kbdxsize,y,x+kbdxsize*2,y+kbdysize*3); LCD_DrawRectangle(x,y+kbdysize,x+kbdxsize*3,y+kbdysize*2); POINT_COLOR=BLUE; for(i=0;i8)return; if(sta)LCD_Fill(x+j*kbdxsize+1,y+i*kbdysize+1,x+j*kbdxsize+kbdxsize-1,y+i*kbdysize+kbdysize-1,GREEN); else LCD_Fill(x+j*kbdxsize+1,y+i*kbdysize+1,x+j*kbdxsize+kbdxsize-1,y+i*kbdysize+kbdysize-1,WHITE); Show_Str_Mid(x+j*kbdxsize,y+4+kbdysize*i,(u8*)kbd_tbl[keyx],16,kbdxsize); Show_Str_Mid(x+j*kbdxsize,y+kbdysize/2+kbdysize*i,(u8*)kbs_t
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值