算法—符号表

定义:符号表是一种存储键值对的数据结构,支持两种操作:插入(put),即将一组新的键值对存入表中;查找(get),即根据给定的键得到相应的值。

1.有序符号表

2.成本模型

查找的成本模型:在学习符号表的实现时,我们会统计比较的次数(等价性测试或是键的相互比较)。在内循环不进行比较(极少)的情况下,我们会统计数组的访问次数。

 3.符号表的用例

/**
 * 符号表用例
 */
public class FrequencyCounter {

	public static void main(String[] args) {
		int minlen = Integer.parseInt(args[0]);	//最小键长
		ST<String, Integer> st = new ST<String, Integer>();
		//构造符号表并统计频率
		while(!StdIn.isEmpty()){
			String word = StdIn.readString();
			//忽略较短的单词
			if(word.length() < minlen){
				continue;
			}
			if(!st.contains(word)){
				st.put(word, 1);
			}
			else{
				st.put(word, st.get(word) + 1);
			}
		}
		//找出出现频率最高的单词
		String max = " ";
		st.put(max, 0);
		for (String word : st.keys()) {
			if(st.get(word) > st.get(max)){
				max = word;
			}
		}
		StdOut.println(max + " " + st.get(max));
	}
}

源码下载

原文地址:https://www.cnblogs.com/joey-hua/p/5004509.html