Java program to find the character that appears the most number of times in a String?

前端 未结 8 939
慢半拍i
慢半拍i 2020-12-22 13:03

So here\'s the code I\'ve got so far...

import java.util.Scanner;
class count{
    public static void main(String args[]){
        Scanner s=new Scanner(Syst         


        
相关标签:
8条回答
  • 2020-12-22 13:24
    • Build the HashMap with Int = number of times that Char appears in the input string; in O(n) where n=length of the input string.
    • Find the maximum value in HashMap in O(m) where m is the number of unique characters in the input string.
    • Overall, the complexity is O(n) since n>m.

    Tips: When you are building the HashMap, at the same time, you can store the maximum value and corresponding character. Still O(n) but the code would be cleaner.

    0 讨论(0)
  • 2020-12-22 13:30
    1. Use Collections. Simple and easy.
    2. Use HashMap <Character,Integer>.
    3. parse the String you have read. For each character in the string, check if it is available in the map (as key). If yes, increment the count, else add the character to the map as key and set the count to 0.
    4. sort the map
    0 讨论(0)
提交回复
热议问题