Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/main/java/com/leetcode/easy/ReverseString344.java
Original file line number Diff line number Diff line change
@@ -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
* <p>
* 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--;
}
}
}
31 changes: 31 additions & 0 deletions src/test/java/com/leetcode/easy/ReverseString344Test.java
Original file line number Diff line number Diff line change
@@ -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);
}
}
Loading