compressed string in java
compressed string in java
input = "aasaaaassgrr";
Output: a2sa4s2gr2
Code:
public class Main {
public static void main(String[] args) {
String input = "aasaaaassgrr";
String compressedString = compressString(input);
System.out.println(compressedString);
}
public static String compressString(String input) {
StringBuilder compressed = new StringBuilder();
int n = input.length();
int c= 1;
for(int i = 0; i<n ; i++){
if(i+1 < n && input.charAt(i) == input.charAt(i+1)){
c++;
}
else{
compressed.append(input.charAt(i));
if(c > 1){
compressed.append(c);
}
c = 1;
}
}
return compressed.toString();
}
}
Output: a2sa4s2gr2
No comments: