Write a program to compress a string. If input is "aabbb" expected output is "a2b3"
The approach:-- Have 2 pointers read and write to the input string.
- Scan the string using read pointer.
- If similar characters are seen keep incrementing a count.
- If character sequence changes, write the character and the count value at the write pointer.
- Finally terminate the string with a null character.
C++ program to compress a string
#include <iostream> using namespace std; int main() { char input[] = "aaabbcccddeeee"; char* read = input; char* write = input; char c = input[0]; int count = 0; while ( *read != '\0' ) { if ( *read == c ) { count++; } else { *write++ = c; *write++ = count + '0'; count = 1; } c = *read; read++; } *write++ = c; *write++ = count + '0'; *write = '\0'; cout << input << endl; return 0; }Output:-
a3b2c3d2e4
Java program to compress a string
In Java, an additional StringBuilder could be used to store the output since String is immutable. Otherwise the approach to compress is the same.package com.stackstalk; public class CompressString { public static String compress(String input) { StringBuilder output = new StringBuilder(); if ( input.length() == 0 ) return output.toString(); char c = input.charAt(0); int count = 0; for ( int index = 0; index < input.length(); index++ ) { if ( input.charAt(index) == c ) count++; else { output.append(c); output.append(count); c = input.charAt(index); count = 1; } } output.append(c); output.append(count); return output.toString(); } public static void main(String[] args) { System.out.println(compress("a")); System.out.println(compress("aaddbbdd")); System.out.println(compress("aabbbbccddde")); } }Output:
a1 a2d2b2d2 a2b4c2d3e1
0 comments:
Post a Comment