Monday 23 May 2016

Print the count of characters in duplicate array


Print the count of characters in a given string in same order. Ex: Input- 'abbaccdbac', Output- 'a3b3c3d1'.

import java.util.Objects;

public class StringUtil {
 // Assumed only ASCII character string
 private static final int ASCII = 255;

 public static String countChars(String str) {
  if (Objects.isNull(str)) {
   return str;
  }

  char[] chars = str.toCharArray();

  int[] counter = new int[ASCII];
  boolean[] isVisited = new boolean[ASCII];

  for (char c : chars) {
   counter[c]++;
  }

  StringBuilder builder = new StringBuilder();

  for (char c : chars) {
   if (isVisited[c]) {
    continue;
   }

   isVisited[c] = true;
   builder.append(c).append(counter[c]);
  }
  return builder.toString();

 }
}


import static org.junit.Assert.*;

import org.junit.Test;

public class StringUtilTest {
 @Test
 public void test1() {
  assertEquals(StringUtil.countChars("abbaccdbac"), "a3b3c3d1");
  assertEquals(StringUtil.countChars("wwyywwyywwzzz"), "w6y4z3");

  assertNull(StringUtil.countChars(null));

 }
}



No comments:

Post a Comment