Add reverseUsingStringBuilder method to reverse a string (#6182)

This commit is contained in:
geetoormvn
2025-02-27 17:45:52 +07:00
committed by GitHub
parent df6da475e2
commit 849ab913c0
2 changed files with 27 additions and 0 deletions

View File

@ -36,4 +36,25 @@ public final class ReverseString {
}
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();
}
}