Saturday 25 July 2015

Check whether a string is funny or not


Suppose ‘S’ is a string and ‘R’ is reverse of string S. The string S is funny if the condition |Si−Si−1|=|Ri−Ri−1| is true for every i from 1 to N−1.

import java.util.Objects;

public class FunnyString {
 public static boolean isFunnyStrings(String str) {
  Objects.nonNull(str);

  String reverse = new StringBuilder(str).reverse().toString();

  for (int i = 1; i < str.length(); i++) {
   int diff1 = Math.abs(str.charAt(i) - str.charAt(i - 1));
   int diff2 = Math.abs(reverse.charAt(i) - reverse.charAt(i - 1));

   if (diff1 != diff2)
    return false;
  }
  return true;
 }
}


Following is the junit test case for above application.
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class FunnyStringTest {

 @Test
 public void test1() {
  assertTrue(FunnyString.isFunnyStrings("acxz"));
  assertFalse(FunnyString.isFunnyStrings("bcxz"));
  assertTrue(FunnyString.isFunnyStrings("bcxy"));
  assertTrue(FunnyString.isFunnyStrings("b"));
  assertTrue(FunnyString.isFunnyStrings("ab"));
  assertTrue(FunnyString.isFunnyStrings("madam"));
  assertFalse(FunnyString.isFunnyStrings("acb"));
 }

 @Test(expected = NullPointerException.class)
 public void test2() {
  FunnyString.isFunnyStrings(null);
 }
}



No comments:

Post a Comment