Thursday 30 July 2015

Find total deleted characters in string

For a given string, remove adjacent characters, if those are same. Return total deleted characters.

For example
AAABBCDD is converted to ABCD (Total characters removed 4 (2 A’s, 1B, 1D))
AAABBC is converted to ABC (Total characters removed 3 (2 A’s 1B))
ABCDDEFFGA is converted to ABCDEFGA (Total characters removed 2 (1D, 1F))
import java.util.Objects;

public class AdjacentCharcatersUtil {
 public static int getDelectedCharCount(String str) {
  Objects.nonNull(str);
  if (str.length() == 1)
   return 0;
  int count = 0;

  char prevChar = str.charAt(0);

  for (int i = 1; i < str.length(); i++) {
   if (prevChar == str.charAt(i)) {
    count++;
    continue;
   }

   prevChar = str.charAt(i);
  }

  return count;
 }
}


Following is the junit test case for above program.

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class AdjacentCharcatersUtilTest {
 @Test
 public void test1() {
  String str1 = "A";
  String str2 = "AA";
  String str3 = "AAA";
  String str4 = "AAAA";
  String str5 = "AAABBCDD";
  String str6 = "AAABBC";
  String str7 = "ABCDDEFFGA";

  assertTrue(AdjacentCharcatersUtil.getDelectedCharCount(str1) == 0);
  assertTrue(AdjacentCharcatersUtil.getDelectedCharCount(str2) == 1);
  assertTrue(AdjacentCharcatersUtil.getDelectedCharCount(str3) == 2);
  assertTrue(AdjacentCharcatersUtil.getDelectedCharCount(str4) == 3);
  assertTrue(AdjacentCharcatersUtil.getDelectedCharCount(str5) == 4);
  assertTrue(AdjacentCharcatersUtil.getDelectedCharCount(str6) == 3);
  assertTrue(AdjacentCharcatersUtil.getDelectedCharCount(str7) == 2);
 }
}

No comments:

Post a Comment