package iostream;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @author mazhen
* @date 2019/9/18 16:29:
* @description
*/
public class StreamTest {
public static void main(String[] args) {
System.out.println(reverse1("abc"));
System.out.println(reverse2("abc"));
System.out.println(reverseNew1("abc"));
System.out.println(reverseNew2("abc"));
}
// 每次取最后一位,然后放在首部拼接
public static String reverse1(String str){
if(null == str || "".equals(str) || str.length()==1){
return str;
}
return str.charAt(str.length()-1)+ reverse1(str.substring(0,str.length()-1));
}
public static String reverse2(String str){
if(null == str || "".equals(str) || str.length()==1){
return str;
}
return reverse2(str.substring(1)) + str.charAt(0);
}
// 这里估计面试官会问,你用了builder的reverse,你知道底层是怎么实现的吗?
// 参考下面的方法 reverseNew2
public static String reverseNew1(String str){
StringBuilder builder = new StringBuilder(str);
return builder.reverse().toString();
}
public static String reverseNew2(String str){
if(null == str || "".equals(str) || str.length()==1){
return str;
}
char[] chars = str.toCharArray();
int length = chars.length;
int middle = length/2;
int j = 0;
for(int i=0; i<middle; i++){
j = length-i-1;
char left = chars[i];
chars[i] = chars [j];
chars[j] = left;
}
String s = new String(chars);
return s;
}
}