zoukankan      html  css  js  c++  java
  • 找出n个字符串中出现次数最多的字符串。

    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());
    
    	}
    
    }
    

      

  • 相关阅读:
    新浪微博学习的知识点
    新浪项目笔记
    2015年10月20日整理知识
    版本管理工具 (git 或者 svn)
    Coding 代码push/commit/pull/git clone
    fileurlwithpath urlwithstring 这俩有啥区别吗
    正则表达式
    地图
    各种杂项
    实时通讯
  • 原文地址:https://www.cnblogs.com/ustc-cui/p/4833732.html
Copyright © 2011-2022 走看看