Quick actions

cmd+k|ctrl+k

Navigation

Languages

Most Frequent Character

Snippet info

Language

Java

Visibility

public

Author

sanjay.yerrolla

Created

2025-02-04T17:01:13.692367Z

Updated

2025-02-04T17:01:13.692367Z

import java.util.*;
class Main {
    public static void main(String[] args) {
        System.out.println(new Main().mostRepeatedCharacter("hello"));
        System.out.println(new Main().mostRepeatedCharacter("bbbazz"));
         System.out.println(new Main().mostRepeatedCharacter("abbqqqad"));
         System.out.println(new Main().mostRepeatedCharacter(""));
         System.out.println(new Main().mostRepeatedCharacter("abbdqqqaddd"));
    }
    
    public String mostRepeatedCharacter(String s){
        Map<Character, Integer> charMap = new HashMap<>();
        int length = s.length();
        for(int i = 0; i<length; i++){
            char ch = s.charAt(i);
            Integer value = charMap.get(ch);
            if(value==null){
                charMap.put(ch,1);
            }
            else{
                
                charMap.put(ch,++value);
            }
        }
        
        int maxValue = Integer.MIN_VALUE;
        String maxKey = null;
        for(Map.Entry<Character,Integer> entry : charMap.entrySet()){
            if(entry.getValue()>maxValue){
                maxValue = entry.getValue();
                maxKey = String.valueOf(entry.getKey());
            }
        }
        return maxKey;
    }
}

//add the string to the map
// loop in to check most repeating character by setting the max value and maxkey
INFO