mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-18 17:31:13 +08:00
Resolve build errors & cleanup structure (#2334)
This commit is contained in:
41
Strings/ReverseString.java
Normal file
41
Strings/ReverseString.java
Normal file
@ -0,0 +1,41 @@
|
||||
package Strings;
|
||||
|
||||
/** Reverse String using different version */
|
||||
public class ReverseString {
|
||||
|
||||
public static void main(String[] args) {
|
||||
assert reverse("abc123").equals("321cba");
|
||||
assert reverse2("abc123").equals("321cba");
|
||||
}
|
||||
|
||||
/**
|
||||
* easiest way to reverses the string str and returns it
|
||||
*
|
||||
* @param str string to be reversed
|
||||
* @return reversed string
|
||||
*/
|
||||
public static String reverse(String str) {
|
||||
return new StringBuilder(str).reverse().toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* second way to reverses the string str and returns it
|
||||
*
|
||||
* @param str string to be reversed
|
||||
* @return reversed string
|
||||
*/
|
||||
public static String reverse2(String str) {
|
||||
|
||||
if (str == null || str.isEmpty()) {
|
||||
return str;
|
||||
}
|
||||
|
||||
char[] value = str.toCharArray();
|
||||
for (int i = 0, j = str.length() - 1; i < j; i++, j--) {
|
||||
char temp = value[i];
|
||||
value[i] = value[j];
|
||||
value[j] = temp;
|
||||
}
|
||||
return new String(value);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user