Advertisement
JeffGrigg

TCSInterviewTest

Jan 30th, 2019
691
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.60 KB | None | 0 0
  1. import junit.framework.TestCase;
  2.  
  3. public class TCSInterviewTest extends TestCase {
  4.  
  5.     private static String transform(final String input) {
  6.  
  7.         final StringBuilder result = new StringBuilder(input.length());
  8.  
  9.         int charCount = 0;
  10.         char lastChar = (char) -1;
  11.  
  12.         for (char thisChar : input.toCharArray()) {
  13.             if (thisChar == lastChar) {
  14.                 ++charCount;
  15.             } else {
  16.                 appendCharacterCount(result, lastChar, charCount);
  17.                 charCount = 1;
  18.                 lastChar = thisChar;
  19.             }
  20.         }
  21.  
  22.         appendCharacterCount(result, lastChar, charCount);
  23.  
  24.         return result.toString();
  25.     }
  26.  
  27.     private static void appendCharacterCount(final StringBuilder result, final char chr, final int count) {
  28.         if (count > 0) {
  29.             result.append(chr);
  30.             if (count > 1) {
  31.                 result.append(count);
  32.             }
  33.         }
  34.     }
  35.  
  36.     public void testInterviewExample() {
  37.         assertEquals("a3b2Bc2d3", transform("aaabbBccddd"));
  38.     }
  39.  
  40.     public void testEmptyString() {
  41.         assertEquals("", transform(""));
  42.     }
  43.  
  44.     public void testOneChar() {
  45.         assertEquals("x", transform("x"));
  46.     }
  47.  
  48.     public void testTwoChar() {
  49.         assertEquals("x2", transform("xx"));
  50.     }
  51.  
  52.     public void testThreeChar() {
  53.         assertEquals("x3", transform("xxx"));
  54.     }
  55.  
  56.     public void testThreeUnique() {
  57.         assertEquals("xyz", transform("xyz"));
  58.     }
  59.  
  60.     public void testXYZZY() {
  61.         assertEquals("xyz2y", transform("xyzzy"));
  62.     }
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement