String compression TC = O(n)
class stringcompression{
public static String printstring(String str){
StringBuilder result=new StringBuilder();
for(int i=0;i<str.length();i++){
Integer count=1;
while(i<str.length()-1&&str.charAt(i)==str.charAt(i+1)){
count++;
i++;
}
result.append(str.charAt(i));
if(count>1){
result.append(count);
}
}
return result.toString();
}
public static void main(String[] args) {
String str="abbcdd";
str=printstring(str);
System.out.print(str);
}
}
Comments
Post a Comment