Coding challenge – Shrinking characters in a String1 min read
Wanna know how to find whether a String has unique characters or not? Check here.
Question: Shrink the text if there are repeated characters next to it. Keep the whitespace as it is. If the shrinked text is greater than the original string, then return the original string.
ex: “aaa bbt ccddd“could be shrunk as a3 b2t1 c2d3
Breakdown:
- The breakdown is simple, we need to loop over all the characters in the string for sure. And while looping, find if the next character is a repeated character of the current character, if so, then increment the counter variable else concat character and number.
package com.zingscoop.challenges.ArraysAndStrings;
public class ShrinkingString {
private static String getShrinkedText(String str) {
int count = 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
// No need to shrink white spaces
if (!Character.isWhitespace(ch)) {
if (i + 1 >= str.length() || ch != str.charAt(i + 1)) {
++count;
sb.append(ch).append(count);
count = 0;
} else {
++count;
}
} else {
sb.append(ch);
count = 0;
}
}
// If shrinnked string greater than original string length, just return original
// string.
return sb.length() > str.length() ? str : sb.toString();
}
public static void main(String[] args) {
String str = "aaa bbt ccddd";
System.out.println(getShrinkedText(str));
String str1 = "Zing Scoop";
System.out.println(getShrinkedText(str1));
}
}
a3 b2t1 c2d3
Zing Scoop
That’s all for this quick coding challenge.
All the above examples are available on github.
Stay subscribed. more to come in this space. Happy Scooping…