Compress strings like "aaabccdddd" to "a3b1c2d4"; return the original string if the compressed version is not shorter.
Solution
Main.java
public class Main {
static String compress(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); ) {
char c = s.charAt(i);
int j = i;
while (j < s.length() && s.charAt(j) == c) j++;
sb.append(c).append(j - i);
i = j;
}
return sb.length() < s.length() ? sb.toString() : s;
}
public static void main(String[] args) {
for (String s : new String[]{"aaabccdddd", "abc", "zzzzzzzzzzzz", ""}) System.out.println("[" + s + "] -> [" + compress(s) + "]");
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!