1 public class ReverseString {
2
3 /**
4 * 字符串指定逆置
5 *
6 * @param str
7 * 字符串
8 * @param start
9 * 开始下标
10 * @param end
11 * 结束下标
12 * @return chsr数组
13 */
14 public static char[] reverseString(String str, int start, int end) {
15 char[] array = str.toCharArray();
16
17 for (int i = start; i < end / 2; i++) {
18 /* array[size - 1 - i]:下标为i值的对称下标的值 */
19 array[i] = (char) (array[i] + array[end - 1 - i]);
20 /*
21 * array[size - 1 - i] = array[i] + array[size - 1 - i] -array[size
22 * - 1 - i]
23 */
24 /* 即:array[size - 1 - i] = array[i] 下标为i的值变为i的对称下标的值 */
25 array[end - 1 - i] = (char) (array[i] - array[end - 1 - i]);
26 /* 同理 */
27 array[i] = (char) (array[i] - array[end - 1 - i]);
28 }
29 return array;
30 }
31
32 /**
33 * 字符串指定逆置(思路:首尾元素互换,一步一步网中间逼近)
34 *
35 * @param str
36 * 字符串
37 * @param start
38 * 开始下标
39 * @param end
40 * 结束下标
41 * @return chsr数组
42 */
43 public static char[] reverseString1(String str, int start, int end) {
44 char[] array = str.toCharArray();
45 while (start <= end) {
46 char temp = array[start];
47 array[start] = array[end];
48 array[end] = temp;
49 end--;
50 start++;
51 }
52 return array;
53 }
54
55 public static void main(String[] args) {
56 String str = "abcdefgffyrhstesrt";
57 System.out.println("转置之前:" + str);
58 char[] array = ReverseString.reverseString(str, 0, str.length());
59 System.out.print("转置之后:");
60 for (int i = 0; i < array.length; i++) {
61 System.out.print(array[i]);
62 }
63 char[] arr = ReverseString.reverseString1(str, 0, str.length()-1);
64 System.out.println();
65 System.out.print("转置之后:");
66 for (int i = 0; i < arr.length; i++) {
67 System.out.print(arr[i]);
68 }
69 }
70
71 }
运行结果:
分析:法一理解起来困难一点,法二通俗易懂