I have a string "aaabbaaaavvvd", it should be compressed to a3b2a4v3d But when I run my code it prints out b3a2v4d3
Strangely, it starts with b instead of a
public class compression {
public String compress(String str){
char chararr[] = str.toCharArray();
StringBuilder sb = new StringBuilder();
int count=1;
char previous = chararr[0];
for(int i=1; i<chararr.length; i++) {
char current = chararr[i];
if(current == previous){
count++;
} else {
sb.append(current).append(count);
count = 1;
}
previous = current;
}
System.out.println(sb.toString());
return sb.toString();
}
public static void main(String args[]){
compression test = new compression();
String str = "aaabbaaaavvvd";
test.compress(str);
}
}
Aucun commentaire:
Enregistrer un commentaire