I have started to try and work out the TopCoder problems. The "StringDup" problem asks us to:
Create a class called StringDup. Given a string made up of ONLY letters and digits, determine which character is repeated the most in the string ('A' is different than 'a'). If there is a tie, the character which appears first in the string (from left to right) should be returned.
Is there any way I can make my solution better or more efficient? Is there something that I have missed? I'm new to Java and I thought this would be a good way to learn.
public class StringDup {
public char getMax(String word)
{
int characterCount = 0;
int maxCharacter = 0;
char maxCharacterChar = '.';
char[] cArray = word.toCharArray();
for(int i =0; i < cArray.length; i++)
{
int characterASCII = (int)cArray[i];
characterCount = 0;
//System.out.print("Chracter ASCII: " + characterASCII + "\n");
for(int x = 0; x < cArray.length; x++)
{
if(characterASCII == (int)cArray[x])
{
characterCount ++;
//System.out.print("Character Count for " + characterASCII + " " + characterCount + "\n");
if(characterCount > maxCharacter)
{
maxCharacter = characterCount;
maxCharacterChar = cArray[i];
}
}
}
}
return maxCharacterChar;
}
}
It is called using the main method.
StringDup frequentChar = new StringDup();
System.out.print(frequentChar.getMax("sssdkljgh"));