How to find the most frequent word in a word stream? [duplicate]

家住魔仙堡 提交于 2019-12-24 05:43:48

问题


Possible Duplicate:
Finding the max repeated element in an array

If there is a word stream, with one word having an occurrence rate of 51% or more, how can we find the most frequent word if only string, and an int can be stored in the memory at a time to help us find it.

We can only access each word a single time, since this is a stream.

No specific language is necessary, but this is mainly intended with Java in mind.

Also I'm not asking for code, just the idea. :)


回答1:


For completeness, implementation in Java of the algorithm presented in the duplicate I pointed at, applied to an example:

public static void main(String[] args) throws InterruptedException {
    List<String> list = Arrays.asList("a", "b", "c", "a", "d", "e", "a", "a", "b", "b", "a");
    int counter = 0;
    String mostFrequentWord = "";
    for (String streamed : list) {
        if (streamed.equals(mostFrequentWord)) {
            counter++;
        } else if (counter == 0) {
            mostFrequentWord = streamed;
            counter = 1;
        } else {
            counter--;
        }
    }
    System.out.println(mostFrequentWord);
}


来源:https://stackoverflow.com/questions/11547686/how-to-find-the-most-frequent-word-in-a-word-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!