华为机试第十四题:HJ14 字符串排序

一、网址链接

牛客----https://www.nowcoder.com/ta/huawei

二、题目描述

①描述

给定 n 个字符串,请对 n 个字符串按照字典序排列。
数据范围: 1<=n<=1000,字符串长度满足 1<=len<=100

②输入描述

输入第一行为一个正整数n(1<=n<=1000),下面n行为n个字符串(字符串长度<=100),字符串中只含有大小写字母。

③输出描述

数据输出n行,输出结果为按照字典序排列的字符串。

④示例一

输入: 9
    cap
    to
    cat
    card
    two
    too
    up
    boat
    boot
输出: boat
    boot
    cap
    card
    cat
    to
    too
    two
    up

三、代码实现

①Java代码实现

import java.util.Scanner;
import java.util.Arrays;
public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
    
    
           int n = Integer.parseInt(scanner.nextLine());
           String[] result = new String[n];
           for (int i = 0;i < n; i++) {
    
    
               result[i] = scanner.nextLine();
           }
           StringBuffer sb = new StringBuffer();
           Arrays.sort(result);
           for (String str : result) {
    
    
               sb.append(str).append('\n');
           }
           System.out.println(sb.toString());
        }
    }
}

②C++代码实现

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
bool cmp(string x,string y)
{
    
    
    //return x.compare(y)<0;   //升序
    return x<y;  
}
int main()
{
    
    
    int n;
    cin>>n;
    string str[1001];
   for(int i=0;i<n;i++)
   {
    
    
       cin>>str[i];
   }
    sort(str,str+n,cmp);//自定义的cmp函数
    for(int i=0;i<n;i++)
    {
    
    
        cout<<str[i]<<endl;
    }
    return 0;
}

③C代码实现

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(void)
{
    
    
    int num = 0, j;
    char cin[101];
    char mystr[1000][101];
    scanf("%d", &num);
    for(int i = 0; i < num; i++)
    {
    
    
        scanf("%s", cin);
        for(j=i-1; j>=0; j--){
    
    
            if(strcmp(cin, mystr[j])<0){
    
    
                strcpy(mystr[j+1], mystr[j]);
            }else{
    
    
                strcpy(mystr[j+1], cin);
                break;
            }
        }
        if(j<0)
        {
    
    
            strcpy(mystr[0],cin);
        }
    }
    for(int i=0; i < num; i++)
    {
    
    
        printf("%s\n", mystr[i]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/faramita_of_mine/article/details/124809748