I created a method for finding the most common character in a string (using hash-map) HashMap
):
public static char getMaxViaHashmap ( String s) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
char maxappearchar = ' ';
for (int i = 0; i < s.length(); i++)
{
if ( map.containsKey(s.charAt(i)))
{
map.put (s.charAt(i), map.get(s.charAt(i)) + 1 );
}
else
{
map.put (s.charAt(i), 1);
}
}
int maxValueInMap=(Collections.max(map.values())); // This will return max value in the Hashmap
for (Entry<Character, Integer> entry : map.entrySet())
{
if (entry.getValue()==maxValueInMap)
{
System.out.println("the max char is : " + entry.getKey() + " and displayed " +maxValueInMap+ " times"); // Print the key with max value
maxappearchar = entry.getKey();
}
}
return maxappearchar;
}
I am primarily concerned withQuestions:
- What is the performance cost (in terms of
O()
\$O()\$)? - What is the memory cost (in terms of
O()
\$O()\$)?
how can the code can be optimized further ?