写出一个程序,接受一个字符串,然后输出该字符串反转后的字符串。(字符串长度不超过1000)
数据范围:0≤n≤1000
要求:空间复杂度O(n),时间复杂度O(n)
java
import java.util.*;
public class Solution {
/**
* 反转字符串
* @param str string字符串
* @return string字符串
*/
public String solve (String str) {
// write code here
int len = str.length();
char[] res = new char[len];
for(int i = 0; i<len; i++){
res[i] = str.charAt(len-1-i);
}
return new String(res);
}
}
js
/**
* 反转字符串
* @param str string字符串
* @return string字符串
*/
function solve( str ) {
// write code here
let res = "";
let len = str.length;
for(let i = 0; i<len; i++){
res = res + str[len-1-i];
}
return res;
}
module.exports = {
solve : solve
};
注意:
- 力扣上输入的是char[],牛客上是String,返回也不同,注意区别
- 数组声明:char[] res = new char[len]
- string长度为length