简体   繁体   中英

how to find the second hieghtest repeated character of a string in java

I want to find the second maximum repeated character of the given string in java

public static void main(String args[]){

    String str = "gautamsingnavinojhail";\*

    write the logic to print second highest repeated character
    *\
    System.out.println(2ndhighestcharacter);// i
}

Take this as a tip to solve your problem.

You can create a Map<Character, Integer> that is map containing the number of times a particular character is present in your string.

Starting from left to right, check if that character is already present in the map. If it is present increment the value by 1. If it is not present put it in the map with a starting value of 1.

Once terminated loop through the map and find the second most used element.

I would suggest to use HashMap here. Below is basic algorithm that can be used to identify highest repeated character.

  1. Create a HashMap, it will store character as key and it's count of occurence as integer value.
  2. Iterate given String character by character
  3. For each character, check if it is already present in the hashmap using containsKey() method o hashmap.
  4. If Yes, just increment the count
  5. if No, then add the character as key to the Map and set its count value to 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM