您的位置:首页 > 其它

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

2015-09-23 22:23 218 查看
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());

}

}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: