题目链接:https://www.nowcoder.com/practice/c3a6afee325e472386a1c4eb1ef987f3
题目描述
写出一个程序,接受一个字符串,然后输出该字符串反转后的字符串。(字符串长度不超过1000)
数据范围: 0≤n≤1000
要求:空间复杂度 O(n),时间复杂度 O(n)
示例 1:
输入:"abcd"
返回值:"dcba"
示例 2:
输入:""
返回值:""
解题代码
方法一:
import java.util.*;
public class Solution {
/**
* 反转字符串
* @param str string字符串
* @return string字符串
*/
public String solve (String str) {
// write code here
char[] ans = str.toCharArray();
for (int i = 0; i < str.length(); i++) {
ans[i] = str.charAt(str.length() - 1 - i);
}
return new String(ans);
}
}
方法二:
import java.util.*;
public class Solution {
/**
* 反转字符串
* @param str string字符串
* @return string字符串
*/
public String solve (String str) {
// write code here
return new StringBuilder(str).reverse().toString();
}
}
方法一:
方法二:

评论区 0