mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 09:06:51 +08:00
Add reverseUsingStringBuilder method to reverse a string (#6182)
This commit is contained in:
@ -36,4 +36,25 @@ public final class ReverseString {
|
|||||||
}
|
}
|
||||||
return new String(value);
|
return new String(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse version 3 the given string using a StringBuilder.
|
||||||
|
* This method converts the string to a character array,
|
||||||
|
* iterates through it in reverse order, and appends each character
|
||||||
|
* to a StringBuilder.
|
||||||
|
*
|
||||||
|
* @param string The input string to be reversed.
|
||||||
|
* @return The reversed string.
|
||||||
|
*/
|
||||||
|
public static String reverse3(String string) {
|
||||||
|
if (string.isEmpty()) {
|
||||||
|
return string;
|
||||||
|
}
|
||||||
|
char[] chars = string.toCharArray();
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
for (int i = string.length() - 1; i >= 0; i--) {
|
||||||
|
sb.append(chars[i]);
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -25,4 +25,10 @@ public class ReverseStringTest {
|
|||||||
public void testReverseString2(String input, String expectedOutput) {
|
public void testReverseString2(String input, String expectedOutput) {
|
||||||
assertEquals(expectedOutput, ReverseString.reverse2(input));
|
assertEquals(expectedOutput, ReverseString.reverse2(input));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ParameterizedTest
|
||||||
|
@MethodSource("testCases")
|
||||||
|
public void testReverseString3(String input, String expectedOutput) {
|
||||||
|
assertEquals(expectedOutput, ReverseString.reverse3(input));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user