题解 | #字符串反转#
字符串反转
https://www.nowcoder.com/practice/e45e078701ab4e4cb49393ae30f1bb04
解题思路
- 读取输入的字符串
- 反转字符串的方法:
- 方法1:使用语言内置的字符串反转函数
- 方法2:手动实现字符串反转
- 方法3:使用栈结构
- 输出反转后的结果
- 注意:
- 字符串长度限制在1000以内
- 只包含小写字母
代码
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str;
getline(cin, str);
// 方法1:使用algorithm的reverse
reverse(str.begin(), str.end());
cout << str << endl;
/* 方法2:手动反转
string result;
for(int i = str.length() - 1; i >= 0; i--) {
result += str[i];
}
cout << result << endl;
*/
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
// 方法1:使用StringBuilder
StringBuilder sb = new StringBuilder(str);
System.out.println(sb.reverse().toString());
/* 方法2:手动反转
char[] chars = str.toCharArray();
for(int i = 0, j = chars.length - 1; i < j; i++, j--) {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
System.out.println(new String(chars));
*/
}
}
# 方法1:使用切片
s = input()
print(s[::-1])
'''
# 方法2:手动反转
s = input()
print(''.join(reversed(s)))
# 方法3:转换为列表反转
s = list(input())
s.reverse()
print(''.join(s))
'''
算法及复杂度
- 算法:字符串反转
- 时间复杂度:
- 其中n为字符串长度
- 空间复杂度:
- 需要存储反转后的字符串