2
\$\begingroup\$

Given a String. we have to print out the letter repetition

Sample input "aaaabbaac"

Sample output "4a2b2a1c"

public void continousWords(String input) {
String sample= input +" ";
String[] sampleList  =   sample.split("");
String temp = sampleList[0];
String result="";
int placeHolder=0;
for(int i=0;i<sampleList.length;i++){

    if(temp.equalsIgnoreCase(sampleList[i])) {
        placeHolder++;

    }
    else {
      result = result+placeHolder+temp;
      placeHolder =1;
      temp = sampleList[i];
    }

}
System.out.println(result);

}

Is there a better way to approach the problem

\$\endgroup\$
1
\$\begingroup\$

This method doesn't need any member of it's class, thus it can be declaced static.

You want to count the repetation of each letter, not the frequency in the string, don't you? At least, that's what I understood from your example result 4a2b2a1c where a is included twice. If you want the frequency 6a2b1c the algorithm would be different.

AN alternative approach to your proposal would be to convert the String in a char array and to analyze that.

public static void continousWords(String input) {
    char[] chars = input.toLowerCase().toCharArray();
    StringBuilder b = new StringBuilder();

    for (int i = 0, count; i < chars.length; i += count) {
        count = 1;
        while (i + count < chars.length && chars[i] == chars[i + count])
            count++;
        b.append(count).append(chars[i]);
    }

    String result = b.toString();
    System.out.println(result);
}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ why is a string Builder preferred here? \$\endgroup\$ – user_xtech007 Mar 1 '18 at 9:32
  • \$\begingroup\$ You don't create new String objects in every loop Iteration, it's faster and consumes less memory. See eg. stackoverflow.com/questions/4645020/… \$\endgroup\$ – milbrandt Mar 1 '18 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.