/** * 反转字符串 遍历整个字符数组 * @param str string字符串 * @return string字符串 */ public String solve1(String str) { String temp = ""; int length = str.length(); for(int i = length - 1; i >= 0; --i) { temp+=str.charAt(i); } return temp; } /** * 同上,字符串+=替换成StringBuilder 的append方法 */ public String solve2(String str) { char[] chars = str.toCharArray(); int size = chars.length; StringBuilder tem = new StringBuilder(); int length = str.length(); for(int i = length - 1; i >= 0; --i) { tem.append(str.charAt(i)); } return tem.toString(); } /** * 同上 */ public String solve3(String str) { char[] chars = str.toCharArray(); int size = chars.length; StringBuilder tem = new StringBuilder(); for (int i = size - 1; i >= 0; --i) { tem.append(chars[i]); } return tem.toString(); } /** * JDK StringBuilder 的reverse()方法 */ public String solve4(String str) { return new StringBuilder(str).reverse().toString(); } /** * */ public String solve5(String str) { char[] array = str.toCharArray(); Stack<Character> stack = new Stack<>(); int length = array.length; for (int i = 0; i < length; i++) { stack.push(array[i]); } array = new char[length]; for (int i = 0; i < length; i++) { array[i] = stack.pop(); } return String.valueOf(array); } /** * 字符数组首尾替换,只需要遍历一半就可以 */ public String solve(String str) { char[] array = str.toCharArray(); int length = array.length; int index = length / 2; char temp; for (int i = 0, j = length - 1; i < index; ++i,--j) { temp = array[i]; array[i] = array[j]; array[j] = temp; } return String.copyValueOf(array); } /** * 字符数组首尾替换,只需要遍历一半就可以 */ public String solve7(String str) { int length = str.length(); int index = length / 2; char[] array = new char[length]; for (int i = 0, j = length - 1; i <= index; ++i,--j) { if (i == j) { array[i] = str.charAt(j); break; } array[i] = str.charAt(j); array[j] = str.charAt(i); } return String.copyValueOf(array); }