Strings-String Compression [codingblocks]
Take as input S, a string. Write a function that does basic string compression. Print the value returned. E.g. for input “aaabbccds” print out a3b2c2ds.
Input FormatA single String S.
Constraints
A string of length between 1 to 1000
Output Format
The compressed String.
Sample Input
aaabbccds
Sample Output
a3b2c2ds
Explanation
In the given sample test case 'a' is repeated 3 times consecutively, 'b' is repeated twice, 'c' is repeated twice. But, 'd' and 's' occurred only once that's why we do not write their occurrence.
Java Code:
IDE Code: https://ide.geeksforgeeks.org/btZOsVDRAd
/* Amit Kumar 14-12-2020 IDE Code: https://ide.geeksforgeeks.org/btZOsVDRAd */ package String; import java.util.Scanner; public class Strings_StringCompression { public static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { String str = scanner.next(); StringBuilder stringBuilder = new StringBuilder(); int count = 1; for (int i=1; i<str.length(); i++) { if (str.charAt(i-1) == str.charAt(i)) { count ++; } else { stringBuilder.append(str.charAt(i-1)); if (count != 1) stringBuilder.append(count); count = 1; } } stringBuilder.append(str.charAt(str.length()-1)); if (count != 1) stringBuilder.append(count); System.out.println(stringBuilder.toString()); } }
Comments
Post a Comment