Here is a new proposed method of compressing strings :
"Anywhere in the string if a character c occurs k number of times consecutively, it can be written as c"
"Anywhere in the string if a character c occurs k number of times consecutively, it can be written as c"
Using this algorithm, your task is to compress the string such that its final length is minimum.
Note that it is not compulsory for you to compress every single character. You may choose to compress whatever characters you want. Only the length of the final string must be minimum.
INPUT
The input is one string that needs to be compressed.
OUTPUT
Print the final compressed string of minimum length
CONSTRAINTS
Length of input string will not be more than 1000.
Input string will consist of lowercase english alphabets only.
Input string will consist of lowercase english alphabets only.
Sample Input 0
bbaannaannaa
Sample Output 0
banana
Explanation 0
string "bbaannaannaa" can be compressed to "banana" by compressing every pair of adjacent equal characters.
SOLUTION :-
import java.io.*;
import java.util.Scanner;;
public class Solution
{
public static void main(String[] args)
{
Solution str = new Solution();
String s1,s2;
Scanner in = new Scanner(System.in);
s1 = in.nextLine();
s2 = s1.replaceAll("\\s","");
str.Compression(s2);
}
public static String Compression(String s)
{
int count = 1;
StringBuilder sb = new StringBuilder();
for (int i = 1; i < s.length()-1 ; i++)
{
if (s.charAt(i) == s.charAt(i - 1))
{
count++;
}
else
{
sb.append(s.charAt(i - 1));
count = 1;
}
}
if (s.length() > 1)
{
if (s.charAt(s.length() - 1) == s.charAt(s.length() - 2))
{
count++;
}
else
{
sb.append(s.charAt(s.length() - 2));
count = 1;
}
sb.append(s.charAt(s.length() - 1));
}
s = sb.toString();
System.out.println(s);
return s;
}
}