Skip to content

Commit

Permalink
Add Reverse String Problem (#14)
Browse files Browse the repository at this point in the history
- Added solution for LeetCode 344 Problem "Reverse String";
- Tests added.
  • Loading branch information
xtenzQ authored Jul 4, 2024
1 parent 0b74b2a commit 0582256
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -110,5 +110,24 @@ public static boolean isSubsequence(String s, String t) {

return i == s.length();
}

/**
* Reverses the input array of characters in-place.
*
* @param s the array of characters to be reversed
* @implNote This method runs in {@code O(n)} time complexity and {@code O(1)} space complexity,
* where {@code n} is the length of {@code s}.
* @see <a href="https://leetcode.com/problems/reverse-string/">344. Reverse String</a>
*/
public static void reverseString(char[] s) {
int i = 0, j = s.length - 1;
while (i < j) {
var temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import static com.xtenzq.arrays.TwoPointers.canBeSummed;
import static com.xtenzq.arrays.TwoPointers.isPalindrome;
import static com.xtenzq.arrays.TwoPointers.mergeSortedArrays;
import static com.xtenzq.arrays.TwoPointers.reverseString;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
Expand Down Expand Up @@ -281,4 +282,52 @@ void testInterleavedNonSubsequence() {
String t = "abcde";
assertFalse(isSubsequence(s, t));
}

@Test
void testReverseStringWithEvenNumberOfCharacters() {
char[] input = {'h', 'e', 'l', 'l', 'o'};
char[] expected = {'o', 'l', 'l', 'e', 'h'};
reverseString(input);
assertArrayEquals(expected, input);
}

@Test
void testReverseStringWithOddNumberOfCharacters() {
char[] input = {'a', 'b', 'c', 'd', 'e'};
char[] expected = {'e', 'd', 'c', 'b', 'a'};
reverseString(input);
assertArrayEquals(expected, input);
}

@Test
void testReverseStringWithSingleCharacter() {
char[] input = {'a'};
char[] expected = {'a'};
reverseString(input);
assertArrayEquals(expected, input);
}

@Test
void testReverseStringWithEmptyArray() {
char[] input = {};
char[] expected = {};
reverseString(input);
assertArrayEquals(expected, input);
}

@Test
void testReverseStringWithRepeatedCharacters() {
char[] input = {'a', 'a', 'a', 'a'};
char[] expected = {'a', 'a', 'a', 'a'};
reverseString(input);
assertArrayEquals(expected, input);
}

@Test
void testReverseStringWithSpecialCharacters() {
char[] input = {'!', '@', '#', '$', '%'};
char[] expected = {'%', '$', '#', '@', '!'};
reverseString(input);
assertArrayEquals(expected, input);
}
}

0 comments on commit 0582256

Please sign in to comment.