Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- class MyCode {
- /**
- * 6 Character Mode
- *
- * Given a string, find the most frequent occurring letter(s) in the string
- *
- * Parameters
- * Input: string {String}
- * Output: {String}
- *
- * Constraints
- * If more than one letter is tied for the most frequent, return a string of all
- * the letters in one string.
- *
- * Time: O(N)
- * Space: O(N)
- *
- * Examples
- * 'hello' --> 'l'
- * 'A walk in the park' --> 'a'
- * 'noon' --> 'no'
- */
- public static void main (String[] args) {
- String one = "hello" ;
- String three = "A walk in the park";
- String four = "Awalkinthepark";
- String two = "noon";
- System.out.println(characterMode(two));
- }
- public static String characterMode(String string) {
- int count = 0;
- string = string.replaceAll("\\s", "");
- string = string.toLowerCase();
- HashMap<Character, Integer> map = new HashMap<Character,Integer>();
- //put chars from string into HashMap for tally
- for(int i = 0; i< string.length(); i++){
- if(map.containsKey(string.charAt(i))){
- count = map.get(string.charAt(i));
- map.put(string.charAt(i), ++count);
- }else{
- map.put(string.charAt(i), 1);
- }
- }
- //get highest value/count in map and append matching key to string
- int max = Collections.max(map.values());
- StringBuilder resultString = new StringBuilder("");
- for (Character c: map.keySet()) {
- if (map.get(c).equals(max)) {
- resultString.append(c);
- }
- }
- return resultString.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement