Assume a string abbcccdddd
is given, there can be a repetition of character, given string needs to be compressed according to repeating of character, the algorithm is also known as Run Length Encoding (RLE) Data Compression Algorithm
.
package org.wesome.dsalgo;
public class CompressString {
static String compressString(String string) {
int sum = 1;
String compressedString = "";
for (int i = 0; i < string.length() - 1; i++) {
if (string.charAt(i) == string.charAt(i + 1)) {
sum++;
} else {
compressedString = compressedString + string.charAt(i) + sum;
sum = 1;
}
}
compressedString = compressedString + string.charAt(string.length() - 1) + sum;
return compressedString;
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class CompressStringTest {
@Test
void CompressStringTest1() {
String compressedString = "weesssoooommmmmeeeeee.......oooooooorrrrrrrrrgggggggggg";
Assertions.assertEquals("w1e2s3o4m5e6.7o8r9g10", CompressString.compressString(compressedString));
}
}
plugins {
id 'java'
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}