Forum

Post 19.05.2009   # 1
Subject CodeFu 2009 Round 2 - Problem 200
200. String Encoding

There was nothing special in this problem.

In the following solution, I put a space character between each pair of different characters in the input string.

Than, split the sequence into smaller strings each of which consists of one ore more repetitions of one and a same character.

Finally construct the resulting string by printing the first character of each of the small strings, followed by the length of that string (if the length is greater than 1).

public class StringEncoding {

public String encode(String s) {

StringBuffer sb = new StringBuffer(s);

if (s.length() == 0) {
return "";
}

// inject spaces into the original String and split
int i = 0;
while(i < sb.length()) {
if (i + 1 < sb.length() && sb.charAt(i) != sb.charAt(i + 1)) {
sb.insert(i + 1, " ");
++i;
}
++i;
}
String[] a = sb.toString().split(" ");

// construct the finall String
StringBuffer result = new StringBuffer("");
for (int j = 0; j < a.length; ++j) {
result.append(a[j].charAt(0));
if (a[j].length() > 1) {
result.append("" + a[j].length());
}
}
return result.toString();
}
}
bilievsk is offline Reply

Please login to post reply.