一、字符串反转
input:“abcde”
output:"edcba"
解决方案:
从后往前,一个个放入到新的char 数组
1 public String forReverse(String original) { 2 char[] temp = original.toCharArray(); 3 StringBuffer sb = new StringBuffer(); 4 int tempLenth = temp.length; 5 for (int i = tempLenth - 1; i >= 0; i--) { 6 sb.append(temp[i]); 7 } 8 return sb.toString(); 9 10 }
两端同时交换(从两边到中间)
1 String input = "Hello world"; 2 char[] temparray = input.toCharArray(); 3 int left, right=0; 4 right = temparray.length-1; 5 6 for (left=0; left < right ; left++ ,right--) 7 { 8 // Swap values of left and right 9 char temp = temparray[left]; 10 temparray[left] = temparray[right]; 11 temparray[right]=temp; 12 } 13 14 for (char c : temparray) 15 System.out.print(c);
两端同时交换(从中间到两端)
1 public String forReverse2(String original) { 2 char[] value = original.toCharArray(); 3 int count = value.length; 4 int n = count - 1; 5 for (int j = (n - 1) >> 1; j >= 0; j--) { 6 int k = n - j; 7 char cj = value[j]; 8 char ck = value[k]; 9 value[j] = ck; 10 value[k] = cj; 11 12 } 13 return String.copyValueOf(value); 14 }
原文:https://www.cnblogs.com/lihao007/p/10865017.html