Results 1 to 4 of 4
  1. #1
    Join Date
    Aug 2013
    Posts
    108
    Rep Power
    0

    Default Very close to solution

    I am trying to print the occurences of each character in the word SUCCESS. I have used hashmap for implementation and the time complexity is O(n).

    Two things I want to know:
    1. Is there a better implementation possible using HashMap?
    2. Why is the output of the program[[U=1, E=1, S=3, C=2] so screwed up? Neither it is in alphabetical order nor it is sorted according to number of occurences. So what is the basis on which it is printing?

    Java Code:
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    public class Occurence {
    	public static void main(String args[])
    	{
    		String s=new String("SUCCESS");
    		Integer k;
    		Map<Character, Integer> hm=new HashMap<Character, Integer>();
    		for(int i=0;i<s.length();i++)
    		{
    			k=1;
    			if(hm.containsKey(s.charAt(i)))
    			{
    				k=hm.get(s.charAt(i));
    				k=k+1;
    				hm.put(s.charAt(i), k);
    			}
    			else
    			{
    				hm.put(s.charAt(i), 1);
    			}
    		}
    		Set set=hm.entrySet();
    		System.out.println(set);
    	}
    }
    Output:
    [U=1, E=1, S=3, C=2]

  2. #2
    allaudin's Avatar
    allaudin is offline Senior Member
    Join Date
    Apr 2013
    Posts
    271
    Rep Power
    0

    Default Re: Very close to solution

    HashSet does not guarantee the order ot its elements. Use TreeSet to make sure that elements will be arranged in sorted order.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,184
    Rep Power
    19

    Default Re: Very close to solution

    Quote Originally Posted by suhaas.mohandos@gmail.com View Post
    Very close to solution
    Please go through the Forum Rules, particularly the third paragraph.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  4. #4
    Join Date
    Aug 2013
    Posts
    108
    Rep Power
    0

Similar Threads

  1. Is POI the right solution ?
    By julien in forum Apache POI
    Replies: 1
    Last Post: 03-19-2012, 04:21 PM
  2. want solution for following
    By abhi7080 in forum New To Java
    Replies: 3
    Last Post: 12-28-2011, 09:07 AM
  3. Replies: 0
    Last Post: 10-28-2011, 02:04 PM
  4. Replies: 13
    Last Post: 04-09-2010, 11:15 AM
  5. Please need solution
    By prithvi in forum New To Java
    Replies: 4
    Last Post: 04-22-2008, 01:27 PM

Posting Permissions

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