From 97f3823f7872b6f84c9f6209462f0a9ccc3c8644 Mon Sep 17 00:00:00 2001 From: Peter Chen Date: Thu, 13 Nov 2025 09:18:34 +0800 Subject: [PATCH] Add solution for "Reverse String" with unit tests. --- .../com/leetcode/easy/ReverseString344.java | 25 +++++++++++++++ .../leetcode/easy/ReverseString344Test.java | 31 +++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 src/main/java/com/leetcode/easy/ReverseString344.java create mode 100644 src/test/java/com/leetcode/easy/ReverseString344Test.java diff --git a/src/main/java/com/leetcode/easy/ReverseString344.java b/src/main/java/com/leetcode/easy/ReverseString344.java new file mode 100644 index 0000000..a1a427d --- /dev/null +++ b/src/main/java/com/leetcode/easy/ReverseString344.java @@ -0,0 +1,25 @@ +// Tags: String, Two Pointers +package com.leetcode.easy; + +public class ReverseString344 { + /** + * Time Complexity: O(n) where n is the length of the array + * - We iterate through half of the array, swapping elements from both ends + * - Each element is visited exactly once + *

+ * Space Complexity: O(1) + * - Only uses a constant amount of extra space (variables l, r, and temp) + * - The reversal is done in-place without allocating additional data structures + */ + public void reverseString(char[] s) { + int l = 0; + int r = s.length - 1; + while (l < r) { + char temp = s[l]; + s[l] = s[r]; + s[r] = temp; + l++; + r--; + } + } +} diff --git a/src/test/java/com/leetcode/easy/ReverseString344Test.java b/src/test/java/com/leetcode/easy/ReverseString344Test.java new file mode 100644 index 0000000..54dba23 --- /dev/null +++ b/src/test/java/com/leetcode/easy/ReverseString344Test.java @@ -0,0 +1,31 @@ +package com.leetcode.easy; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +public class ReverseString344Test { + private ReverseString344 solution; + + @BeforeEach + void setUp() { + solution = new ReverseString344(); + } + + @Test + void testReverseString_Example1() { + char[] input = {'h', 'e', 'l', 'l', 'o'}; + char[] expected = {'o', 'l', 'l', 'e', 'h'}; + solution.reverseString(input); + assertArrayEquals(expected, input); + } + + @Test + void testReverseString_Example2() { + char[] input = {'H', 'a', 'n', 'n', 'a', 'h'}; + char[] expected = {'h', 'a', 'n', 'n', 'a', 'H'}; + solution.reverseString(input); + assertArrayEquals(expected, input); + } +}