校招算法笔面试 | 华为机试-字符串排序

题目

题目链接

解题思路

  1. 读取输入的字符串个数 n n n
  2. 读取 n n n 个字符串并存储到数组或列表中
  3. 对字符串列表进行排序:
    • 使用语言内置的排序函数
    • 排序时大小写字母会自动按ASCII码排序(大写字母在小写字母前)
  4. 按顺序输出排序后的字符串

代码

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int main() {
    int n;
    cin >> n;
    
    vector<string> strings;
    string str;
    
    // 读取字符串
    for(int i = 0; i < n; i++) {
        cin >> str;
        strings.push_back(str);
    }
    
    // 排序
    sort(strings.begin(), strings.end());
    
    // 输出结果
    for(const string& s : strings) {
        cout << s << endl;
    }
    
    return 0;
}
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        
        String[] strings = new String[n];
        
        // 读取字符串
        for(int i = 0; i < n; i++) {
            strings[i] = sc.next();
        }
        
        // 排序
        Arrays.sort(strings);
        
        // 输出结果
        for(String s : strings) {
            System.out.println(s);
        }
    }
}
# 读取字符串个数
n = int(input())

# 读取所有字符串
strings = []
for _ in range(n):
    strings.append(input())

# 排序并输出
strings.sort()
for s in strings:
    print(s)

算法及复杂度

  • 算法:使用语言内置的排序算法
  • 时间复杂度: O ( n log ⁡ n ) \mathcal{O}(n\log n) O(nlogn) - 排序的时间复杂度
  • 空间复杂度: O ( n ) \mathcal{O}(n) O(n) - 需要存储n个字符串
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值