2021-09-26 17:26:59 +08:00
|
|
|
package Strings;
|
2020-08-26 00:05:11 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
/** Reverse String using different version */
|
2020-08-26 00:05:11 +08:00
|
|
|
public class ReverseString {
|
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
public static void main(String[] args) {
|
|
|
|
assert reverse("abc123").equals("321cba");
|
|
|
|
assert reverse2("abc123").equals("321cba");
|
|
|
|
}
|
2020-08-26 00:05:11 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
/**
|
|
|
|
* 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();
|
|
|
|
}
|
2020-08-26 00:05:11 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
/**
|
|
|
|
* 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) {
|
2020-08-26 00:05:11 +08:00
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
if (str == null || str.isEmpty()) {
|
|
|
|
return str;
|
2020-08-26 00:05:11 +08:00
|
|
|
}
|
|
|
|
|
2020-10-24 18:23:28 +08:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
}
|