写出一个程序,接受一个字符串,然后输出该字符串反转后的字符串。(字符串长度不超过1000)
数据范围:
要求:空间复杂度
,时间复杂度
public class Solution {
public String solve (String str) {
if(str.length()<=1) return str;
int left=0;
int right=str.length()-1;
StringBuffer sb=new StringBuffer(str);
while(left<=right){
char temp=sb.charAt(right);
sb.setCharAt(right,sb.charAt(left));
sb.setCharAt(left,temp);
left++;
right--;
}
return sb.toString();
}
}
public class Solution {
/**
* 反转字符串
* @param str string字符串
* @return string字符串
*/
public String solve (String str) {
//把String变成char[]
char[] charr=str.toCharArray();
int l=0;
int r=charr.length-1;
char tmp;
while(l<r){
tmp=charr[l];
charr[l]=charr[r];
charr[r]=tmp;
l++;
r--;
}
String ans=String.valueOf(charr);
return ans;
}
} return new StringBuffer(str).reverse().toString();java一句话解决
import java.util.*;
public class Solution {
public String solve (String str) {
StringBuilder sb = new StringBuilder(str);
return sb.reverse().toString();
}
} public String solve (String str) {
// write code here
char[] cs = new char[str.length()];
for(int i=0;i<cs.length;i++){
cs[i]=str.charAt(cs.length-1-i);
}
return String.valueOf(cs);
} 入门级的题居然没有一次通过,我实在太low了
import java.util.*;
public class Solution {
/**
* 反转字符串
* @param str string字符串
* @return string字符串
*/
public String solve (String str) {
// write code here
if(str.length() == 0 || str.length() == 1){
return str;
}
char[] chr = str.toCharArray();
reverse(chr);
return String.valueOf(chr);
}
public void reverse(char[] chr){
int l = 0;
int r = chr.length -1;
while(l < r){
char temp = chr[l];
chr[l] = chr[r];
chr[r] = temp;
l++;
r--;
}
}
} import java.util.*;
public class Solution {
/**
* 反转字符串
* @param str string字符串
* @return string字符串
*/
public String solve (String str) {
// write code here
StringBuilder strResult = new StringBuilder();
char[] chars = str.toCharArray();
for(int i = chars.length-1;i>=0;i--){
strResult.append(chars[i]);
}
return strResult.toString();
}
}