|
| 1 | +import org.junit.Assert; |
| 2 | +import org.junit.Test; |
| 3 | + |
| 4 | +/** |
| 5 | + * Java Program to reverse a String in place, |
| 6 | + * without any additional buffer in Java. |
| 7 | + * |
| 8 | + * @author WINDOWS 8 |
| 9 | + * |
| 10 | + */ |
| 11 | +public class StringReversal { |
| 12 | + |
| 13 | + /** |
| 14 | + * Java method to reverse a String in place |
| 15 | + * @param str |
| 16 | + * @return reverse of String |
| 17 | + */ |
| 18 | + public static String reverse(String str) { |
| 19 | + if(str == null || str.isEmpty()){ |
| 20 | + return str; |
| 21 | + } |
| 22 | + char[] characters = str.toCharArray(); |
| 23 | + int i = 0; |
| 24 | + int j = characters.length - 1; |
| 25 | + while (i < j) { |
| 26 | + swap(characters, i, j); |
| 27 | + i++; |
| 28 | + j--; |
| 29 | + } |
| 30 | + return new String(characters); |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Java method to swap two numbers in given array |
| 35 | + * @param str |
| 36 | + * @param i |
| 37 | + * @param j |
| 38 | + */ |
| 39 | + private static void swap(char[] str, int i, int j) { |
| 40 | + char temp = str[i]; |
| 41 | + str[i] = str[j]; |
| 42 | + str[j] = temp; |
| 43 | + } |
| 44 | + |
| 45 | + @Test |
| 46 | + public void reverseEmptyString(){ |
| 47 | + Assert.assertEquals("", reverse("")); |
| 48 | + } |
| 49 | + |
| 50 | + @Test |
| 51 | + public void reverseString(){ |
| 52 | + Assert.assertEquals("cba", reverse("abc")); |
| 53 | + } |
| 54 | + |
| 55 | + @Test |
| 56 | + public void reverseNullString(){ |
| 57 | + Assert.assertEquals(null, reverse(null)); |
| 58 | + } |
| 59 | + |
| 60 | + @Test |
| 61 | + public void reversePalindromeString(){ |
| 62 | + Assert.assertEquals("aba", reverse("aba")); |
| 63 | + } |
| 64 | + |
| 65 | + @Test |
| 66 | + public void reverseSameCharacterString(){ |
| 67 | + Assert.assertEquals("aaa", reverse("aaa")); |
| 68 | + } |
| 69 | + |
| 70 | + @Test |
| 71 | + public void reverseAnagramString(){ |
| 72 | + Assert.assertEquals("mary", reverse("yram")); |
| 73 | + } |
| 74 | +} |
0 commit comments