Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import junit.framework.TestCase;
- public class TCSInterviewTest extends TestCase {
- private static String transform(final String input) {
- final StringBuilder result = new StringBuilder(input.length());
- int charCount = 0;
- char lastChar = (char) -1;
- for (char thisChar : input.toCharArray()) {
- if (thisChar == lastChar) {
- ++charCount;
- } else {
- appendCharacterCount(result, lastChar, charCount);
- charCount = 1;
- lastChar = thisChar;
- }
- }
- appendCharacterCount(result, lastChar, charCount);
- return result.toString();
- }
- private static void appendCharacterCount(final StringBuilder result, final char chr, final int count) {
- if (count > 0) {
- result.append(chr);
- if (count > 1) {
- result.append(count);
- }
- }
- }
- public void testInterviewExample() {
- assertEquals("a3b2Bc2d3", transform("aaabbBccddd"));
- }
- public void testEmptyString() {
- assertEquals("", transform(""));
- }
- public void testOneChar() {
- assertEquals("x", transform("x"));
- }
- public void testTwoChar() {
- assertEquals("x2", transform("xx"));
- }
- public void testThreeChar() {
- assertEquals("x3", transform("xxx"));
- }
- public void testThreeUnique() {
- assertEquals("xyz", transform("xyz"));
- }
- public void testXYZZY() {
- assertEquals("xyz2y", transform("xyzzy"));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement