Thứ Hai, 25 tháng 8, 2014

Java Program To Find Repeating characters in String

For example if a string like"shashi kumar" ,we need to find repeating characters i'e 
s repeated 2 times,a repeated 2 times,h repeated 2 times.

Solution:

1.Basically you can do thing using bruteforce approach  but it takes probably O(n^2) time .
2.For an efficiency you can do this in O(n) if you use collection frame Work.
3.Here am using HashMap() class of collection frame work ,which was defined in java.util package.
 4.The logic here is , first converting string to a character array ,then inserting it into hashmap(key,value) pair.
5.The insertion process in such a way that if a value is already present in map ,am increasing th count by using get(character)+adding1.

program:

package logics;
import java.util.*;

public class repeatingCharactorsInString {

    public static void  main(String []args)
    {
        String data="shashi kumar";
        char ch[]=data.toCharArray();
        Map<Character, Integer> m=new HashMap<Character, Integer>();
        for(char c:ch)
        {
            if(m.containsKey(c))//checking already have been there in a string
            {
                m.put(c, m.get(c)+1);
            }
            else
            {
                m.put(c, 1);
            }
        }
        //now printing repeated values.
        Iterator<Character> i=m.keySet().iterator();
        while(i.hasNext())
        {
            Object key=i.next();
            Integer val=m.get(key);
            if(val>1)
            {
            System.out.println(key+" repeated ----->"+val);
            }
        }
       
    }
}

output:
-----------------------------
s repeated ----->2
a repeated ----->2
h repeated ----->2


 

Không có nhận xét nào:

Đăng nhận xét