Skip to content

Commit

Permalink
Shrink a string
Browse files Browse the repository at this point in the history
  • Loading branch information
AnghelLeonard committed Feb 22, 2020
1 parent d490795 commit 1948beb
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
14 changes: 14 additions & 0 deletions Chapter10/StringShrinker/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>coding.challenge</groupId>
<artifactId>StringShrinker</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>13</maven.compiler.source>
<maven.compiler.target>13</maven.compiler.target>
</properties>
<name>StringShrinker</name>
</project>
13 changes: 13 additions & 0 deletions Chapter10/StringShrinker/src/main/java/coding/challenge/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package coding.challenge;

public class Main {

public static void main(String[] args) {

String str = "abbb vvvv s rttt rr eeee f";

System.out.println("Initial: " + str);
System.out.println("Result : " + Strings.shrink(str));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package coding.challenge;

public final class Strings {

private Strings() {
throw new AssertionError("Cannot be instantiated");
}

public static String shrink(String str) {

if (str == null || str.isBlank()) {
return "";
}

StringBuilder result = new StringBuilder();

int count = 0;
for (int i = 0; i < str.length(); i++) {

count++;

// we don't count whitespaces, we just copy them
if (!Character.isWhitespace(str.charAt(i))) {

// if there are no more characters or the next character
// is different from the counted one
if ((i + 1) >= str.length()
|| str.charAt(i) != str.charAt(i + 1)) {

// append to the final result the counted character
// and number of consecutive occurrences
result.append(str.charAt(i))
.append(count);

// reset the counter since this sequence was appended to the result
count = 0;
}
} else {
result.append(str.charAt(i));
count = 0;
}
}

// return the result only if it is shorter than the given string
return result.length() > str.length()
? str : result.toString();
}
}

0 comments on commit 1948beb

Please sign in to comment.