解题思路
- 读取输入字符串
- 将字符串转换为字符数组
- 使用排序算法对字符按ASCII码值从小到大排序
- 输出排序后的字符串
注意:
- ASCII码顺序:数字(48-57) < 大写字母(65-90) < 小写字母(97-122)
- 可以直接使用语言内置的排序函数,因为字符比较默认就是按ASCII值比较
代码
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str;
cin >> str;
// 转换为字符数组并排序
sort(str.begin(), str.end());
cout << str << endl;
return 0;
}
def sort_string():
# 读取输入并排序
s = input()
sorted_s = ''.join(sorted(s))
print(sorted_s)
if __name__ == "__main__":
sort_string()
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
// 转换为字符数组
char[] chars = str.toCharArray();
// 排序
Arrays.sort(chars);
System.out.println(new String(chars));
}
}
算法及复杂度
- 算法:字符排序
- 时间复杂度:
,其中 n 为字符串长度
- 空间复杂度:
,需要存储字符数组