Finding repeated words on a string and counting the repetitions

后端 未结 29 874
梦谈多话
梦谈多话 2021-02-05 17:49

I need to find repeated words on a string, and then count how many times they were repeated. So basically, if the input string is this:

String s = \"House, House         


        
29条回答
  •  清酒与你
    2021-02-05 18:24

    For Strings with no space, we can use the below mentioned code

    private static void findRecurrence(String input) {
        final Map map = new LinkedHashMap<>();
        for(int i=0; i= 2) {
                String word = input.substring(startPointer, pointer);
                if(map.containsKey(word)){
                    map.put(word, map.get(word)+1);
                }else{
                    map.put(word, 1);
                }
                i=pointer;
            }else{
                i++;
            }
        }
        for(Map.Entry entry : map.entrySet()){
            System.out.println(entry.getKey() + " = " + (entry.getValue()+1));
        }
    }
    

    Passing some input as "hahaha" or "ba na na" or "xxxyyyzzzxxxzzz" give the desired output.

提交回复
热议问题