Thursday 30 July 2015

Remove same adjacent character in a string.

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

For example,
AAABBCDD is converted to ABCD
AAABBC is converted to ABC
ABCDDEFFGA is converted to ABCDEFGA
import java.util.Objects;

public class AdjacentCharcaters {

 public static String getTransformedString(String str){
  Objects.nonNull(str);
  if(str.length() == 1)
   return str;
  
  StringBuilder builder = new StringBuilder();
  
  char prevChar = str.charAt(0);
  builder = builder.append(prevChar);
  
  for(int i=1; i<str.length(); i++){
   if(prevChar == str.charAt(i))
    continue;
   prevChar = str.charAt(i);
   builder = builder.append(prevChar);
  }
  
  return builder.toString();
 }
}


Following is the junit test case for above application.

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class AdjacentCharcatersTest {

 @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";

  String expected1 = "A";
  String expected5 = "ABCD";
  String expected6 = "ABC";
  String expected7 = "ABCDEFGA";

  assertEquals(expected1, AdjacentCharcaters.getTransformedString(str1));
  assertEquals(expected1, AdjacentCharcaters.getTransformedString(str2));
  assertEquals(expected1, AdjacentCharcaters.getTransformedString(str3));
  assertEquals(expected1, AdjacentCharcaters.getTransformedString(str4));
  assertEquals(expected5, AdjacentCharcaters.getTransformedString(str5));
  assertEquals(expected6, AdjacentCharcaters.getTransformedString(str6));
  assertEquals(expected7, AdjacentCharcaters.getTransformedString(str7));

 }
}


No comments:

Post a Comment