可以全部返回转,怎么不可以局部翻转?哪里的问题?
public class StringDemo {
/*
* 字符串翻转
* 1.将字符串变成数组
* 2.对数组翻转
* 3.将数组变成字符串
*/
public static void main(String[] args) {
String str = "abcd efgh";
System.out.println(reverseString(str,0,1));//怎么不可以局部翻转
}
public static String reverseString(String s,int start,int end){
char[] chars = s.toCharArray();
reverse(chars,start,end);
return (new String(chars));
}
public static String reverseString(String s){
return reverseString (s,0,s.length());
}
private static void reverse(char[] arr, int x, int y) {
for(int start=x,end=y-1;start<end;start++,end--){
swap(arr,start,end);
}
}
private static void swap(char[] arr, int x, int y) {
char temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
} |