码迷,mamicode.com
首页 > 其他好文 > 详细

找出n个字符串中出现次数最多的字符串。

时间:2015-09-23 23:27:57      阅读:575      评论:0      收藏:0      [点我收藏+]

标签:

1. 找出n个字符串中出现次数最多的字符串。

C/C++:

char* find(char **data,int n);

Java:

String find(String data[]);

说明:

1. data是字符串数组,n是数组中字符串的个数,返回值为出现次数最多的字符串。

2. 若结果有多个,返回任意一个即可

3. 不得使用任何库函数/API,如需使用类似功能, 请自行实现

4. 算法效率尽可能高,尽量少的使用内存空间

5. 必须要有代码注释和算法说明。

例如:data里面的数据是{“paper”,”cup”,”book”,”cup”,”pen”,”book”}。n = 6。返回结果为”cup”或”book”。

 

package offer;

/**
 * 解决问题:找出n个字符串中出现次数最多的字符串。 解决思路:通过对字典树进行改造,在提高效率的同时,完成对出现最多自身的统计。
 * 
 * 
 * @author cxx
 *
 */
public class FindMaxCountWord {

	private TrieNode root = new TrieNode();// 字典树的根节点
	private int max;// 统计出现的最大次数
	private String maxWord;// 出现最大次数的字符串

	protected class TrieNode {
		protected int words;// 统计从根到该节点的单词出现的个数
		protected TrieNode[] edges;// 存放该节点的子节点

		TrieNode() {
			this.words = 0;
			edges = new TrieNode[26];// 题目对于字符没有做出限制,这里默认全是小写字符
			for (int i = 0; i < edges.length; i++) {
				edges[i] = null;
			}
		}
	}

	// 向字典树中添加单词
	public void addWord(String word) {
		addWord(root, word, word);// 第二个word是个冗余参数,为了记录增加的单词
	}

	private void addWord(TrieNode vertex, String word, String wordcount) {
		if (word.length() == 0) {
			vertex.words++;
			if (max < vertex.words) {
				max = vertex.words;
				maxWord = wordcount;
			}
		} else {
			char c = word.charAt(0);
			c = Character.toLowerCase(c);
			int index = c - ‘a‘;
			if (vertex.edges[index] == null) { // 构建节点的路径
				vertex.edges[index] = new TrieNode();
			}
			addWord(vertex.edges[index], word.substring(1), wordcount); 
		}
	}

	// 返回出现次数最大的单词
	public String maxCountWord() {
		return maxWord;
	}

	public static void main(String args[]) // Just used for test
	{
		FindMaxCountWord trie = new FindMaxCountWord();

		String[] data = { "paper", "ckup", "book", "cup", "pen", "book" };

		for (int i = 0; i < data.length; i++) {
			trie.addWord(data[i]);
		}

		System.out.println(trie.maxCountWord());

	}

}

  

找出n个字符串中出现次数最多的字符串。

标签:

原文地址:http://www.cnblogs.com/ustc-cui/p/4833732.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!