Saturday 13 December 2014

Given a string as input, return a string containing the characters that appear at least twice in the string char2Times("hello") = "l" (l is present at least twice) char2Times("trisect teaches code ") = "tsec" (t,e,c are present at least twice) char2Times("India") = "" (no char is present at least twice)

public class Char2Times {
    static String testcase="ssuunnnilkm  3434 66 ## zxqho";
    public static void main(String args[]){
        Char2Times testInstance=new Char2Times();
        String result=testInstance.checkString(testcase);
        System.out.println(result);
       
    }
    public String checkString(String str){
        String holdMaxChar="";//store the max occurence of char in string
        char holdEachChar=' ';//hold each char of the string
        int count=0,i=0;
        while(str.length()>0){//check the string len coz each time the string getting shorter
            holdEachChar=str.charAt(i);//hold the first char of string each time
            String stringValueOf=str.valueOf(holdEachChar);//convert the char to string
            for(int j=0;j<str.length();j++){//loop will check the number of occurence of each  char
                if(str.regionMatches(j,stringValueOf,0, stringValueOf.length())){//this will check the number of occurence of char from j=0, each time and when j increases from that point
                    count++;//increase the count if find the char
                }
            }
            str=str.replace(stringValueOf,"");//replace with white space the char checked
            str=str.replaceAll("\\s+","");//wipe out all white space
            if(count>=2){//if more than two times found the char inside the string then move on
                holdMaxChar=holdMaxChar+stringValueOf;//store the max char
               
            }
            count=0;//coz each time the loop will check the occurence starts from 0 count value
        } 
    return holdMaxChar;       
    }       
}
    

No comments:

Post a Comment