预备知识
String[] str = {"asd","qwe","ere"};
StringBuffer sb =new StringBuffer();
for(int i = 0; i < str.length; i++){
sb.appeng(str[i]);
}
sb.toString();
char[] data = {'a','s','e'};
String str = new String(data)
String str = "absddd"
char[] ans = str.toCharArray()
1. 代码:
- 新建一个和str长度大小相同的temp字符数组,循环遍历将strt倒序赋值给temp里,空间复杂度为O(n)
public String solve (String str) {
int len = str.length();
if(len >1000){
return null;
}
char[] temp = str.toCharArray();
for(int i=0;i<len;i++){
temp[i] = str.charAt(len-1-i);
}
String res = new String(temp);
return res;
}
2. 原地实现,不开辟新空间
- 头尾交换
char[] temp = str.toCharArray();
for(int i = 0 ; i < len/2 ;i++){
char t = temp[i]
temp[i] = temp[len-1-i]
temp[len-1-i] = t;
}
return new String(temp)