Advertisement
gelita

Mode of characters in string (highest frequency char in stri

Feb 9th, 2020
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.74 KB | None | 0 0
  1.  
  2.   import java.io.*;
  3.   import java.util.*;
  4.  
  5.   class MyCode {
  6.  
  7.    /**
  8.     * 6 Character Mode
  9.     *
  10.     * Given a string, find the most frequent occurring letter(s) in the string
  11.     *
  12.     * Parameters
  13.     * Input: string {String}
  14.     * Output: {String}
  15.     *
  16.     * Constraints
  17.     * If more than one letter is tied for the most frequent, return a string of all
  18.     * the letters in one string.
  19.     *
  20.     * Time: O(N)
  21.     * Space: O(N)
  22.     *
  23.     * Examples
  24.     * 'hello' --> 'l'
  25.     * 'A walk in the park' --> 'a'
  26.     * 'noon' --> 'no'
  27.     */    
  28.     public static void main (String[] args) {
  29.       String one = "hello" ;
  30.       String three = "A walk in the park";
  31.       String four = "Awalkinthepark";
  32.      
  33.       String two = "noon";
  34.       System.out.println(characterMode(two));  
  35.     }
  36.      public static String characterMode(String string) {
  37.        int count = 0;
  38.        string = string.replaceAll("\\s", "");
  39.        string = string.toLowerCase();
  40.        HashMap<Character, Integer> map = new HashMap<Character,Integer>();
  41.        //put chars from string into HashMap for tally
  42.        for(int i = 0; i< string.length(); i++){
  43.          if(map.containsKey(string.charAt(i))){
  44.            count = map.get(string.charAt(i));
  45.            map.put(string.charAt(i), ++count);
  46.          }else{
  47.             map.put(string.charAt(i), 1);
  48.          }
  49.        }
  50.        //get highest value/count in map and append matching key to string
  51.        int max = Collections.max(map.values());
  52.        StringBuilder resultString = new StringBuilder("");
  53.        for (Character c: map.keySet()) {
  54.           if (map.get(c).equals(max)) {
  55.             resultString.append(c);
  56.           }
  57.       }
  58.        return resultString.toString();
  59.      }
  60.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement