Results 1 to 4 of 4
  1. #1
    Yakg is offline Member
    Join Date
    Dec 2010
    Posts
    59
    Rep Power
    0

    Default is there a more efficient way?

    Hi, I've been asked to build s method that finds the most frequent used letter (char).
    I thought about a nested for loop that has two pointers and compares between the first and the second in the common way and when finding a match, increment a counter by one. Eventually returns the letter that counted the most.

    My question is about the complexities because I'm not sure this is the most efficient way, and Ideas?

    Thanks.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    I would use a HashMap<Character, Integer> and increment each char's count when a char is encountered. Either that or an array of int.

  3. #3
    Yakg is offline Member
    Join Date
    Dec 2010
    Posts
    59
    Rep Power
    0

    Default unfortunately I'm not allowed

    to use that, I can use the String methods for my task.

    I thought about creating an array but then if I go through it and then sort it, the complexity will be the same..

    I thought also about going through the list ones and store each char in its designated place, for ex. if I come across 'a', an int a variable will be incremented and so on, so the outcome will look like:
    a = 3
    b = 1
    c = 2

    Then all I have to do is return the highest valued letter, in that case 'a'
    but how do I do that without going through the list again (for complexity reasons)?

    By the way it's recursive..

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    You could use an array and use the 0th item for 'a', the next item for 'b'. The array index can easily be obtained by using char math, since the index to the array would be nothing more than your char - 'a' (assuming all chars are lower-case, and if not, first converting them to lower case). Then you could increment the array item associated with that index. When done, you could easily find the largest item in the array, and via its index, know which char it represents.

Similar Threads

  1. Need help making program more efficient
    By cid in forum New To Java
    Replies: 4
    Last Post: 06-30-2010, 08:22 PM
  2. Replies: 1
    Last Post: 03-22-2010, 09:21 AM
  3. Need a simple and efficient solution.
    By Samgetsmoney in forum New To Java
    Replies: 9
    Last Post: 02-20-2009, 02:18 AM
  4. Efficient Perfect Number
    By Lite3864 in forum New To Java
    Replies: 4
    Last Post: 11-23-2008, 02:07 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •