找出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”。
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()); } }
相关文章推荐
- 浅谈Java中的hashcode方法
- OWIN初探
- xtrabackup实现mysql数据库的完全备份和增量备份
- ubuntu下source、sh、bash、./执行脚本的区别
- Light oj 1119 - Pimp My Ride(状压dp)
- Python:staticmethod vs classmethod
- php基础---多态
- 网络请求的封装
- css.day03
- uva 12168 - Cat vs. Dog(二分图匹配)
- 简单工厂模式、工厂方法模式和抽象工厂模式小结
- MySQL函数的使用
- 有一个序列集合,如[1,1,1,2,3,3,2]统计这个集合中所有元素出现的次数,如1出现的次数为3次,2出现2次
- xss<script>alert("11");</script>
- 河南理工大学14级数据结构第一次上机实验课题试验
- windows手动启动服务方法
- vagrant启动报错The following SSH command responded with a non-zero exit status.解决方法
- NYOJ 518 取球游戏(博弈问题)
- 如何编写高质量JavaScript代码
- 韩顺平 java 第十七讲 排序