- /*
- *练习二:将字符串指定的部分反转
- *思路:将字符串变成数组,将数组反转,将数组变成字符串
- */
- public static String reverseString(String s,int start,int end){
- char[] chs = s.toCharArray();
- reverse(chs,start,end);
- return new String(chs);
- }
- private static void reverse(char[] arr,int x,int y){
- for(int start=x,end=y-1;start<end;start++,end--){//y-1,包含头不包含尾,约定俗成
- swap(arr,start,end); //java定义成这样方便传length得到length-1
- }
- }
- private static void swap(char[] arr,int x,int y){
- char temp = arr[x];
- arr[x] = arr[y];
- arr[y] = temp;
- }
- public static String reverseString(String s){
- return reverseString(s,0,s.length());
- }
复制代码
|