Le Phuoc Le Phuoc - 3 months ago 9
Java Question

Transform the string "AABSSSD" to be "2AB3SD"

Please help me, I want to transfrom the string

AABSSSD
to be
2AB3SD
(someone called it was encryption).
This is how I resolve it:

public class TransformString {

public static void main(String[] args) {
String str = "AABSSSD";
StringBuilder newStr = new StringBuilder("");
char temp = str.charAt(0);
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (temp == str.charAt(i)) {
count++;
} else {
newStr.append(count);
newStr.append(temp);
count = 0;
}
temp = str.charAt(i);
if(i == (str.length() - 1)){
newStr.append(str.charAt(i));
}
}
String x = String.valueOf(newStr);
x = x.replace("0", "");
System.out.print(x);
}
}


but the output is,

2AB2SD


This result is not exactly look like I want.

Please help me transform
"AABSSSD"
to
"2AB3SD"
.

Answer

In your else part you should set counter to 1 instead of 0 as new character is having it's first occurrence,

else {
    newStr.append(count);
    newStr.append(temp);
    count = 1;//Just change this
}

and replace 1 instead of 0 from the String x = x.replace("1", ""); because 0A does not look valid as A occurred once in the String so it should be 1A instead of 0A.

Comments