网易校招真题——两种排序方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Hay54/article/details/82178334

牛客编程题——两种排序方法

题目描述

考拉有n个字符串字符串,任意两个字符串长度都是不同的。考拉最近学习到有两种字符串的排序方法:
1.根据字符串的字典序排序。例如: “car”< “carriage” < “cats” < “doggies < “koala”
2.根据字符串的长度排序。例如: “car” < “cats” < “koala” < “doggies” < “carriage” 考拉想知道自己的这些字符串排列顺序是否满足这两种排序方法,考拉要忙着吃树叶,所以需要你来帮忙验证。

输入描述:

输入第一行为字符串个数n(n ≤ 100) 接下来的n行,每行一个字符串,字符串长度均小于100,均由小写字母组成

输出描述:

如果这些字符串是根据字典序排列而不是根据长度排列输出”lexicographically”,

如果根据长度排列而不是字典序排列输出”lengths”,

如果两种方式都符合输出”both”,否则输出”none”

示例1

输入

3
a
aa
bbb
输出

both

c++代码如下:

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int dictsort(vector<string> v){
    vector<string> t;
    t=v;
    sort(t.begin(),t.end());
    if(t==v)
        return 1;
    else
        return 0;

}

void vsort(vector<string> &v){
    int count=v.size();
    for (int i = 0; i < count-1; ++i)
    {
        for (int j = 0; j < count-i-1; ++j)
        {
            if(v[j].length()>v[j+1].length()){
                string tmp=v[j];
                v[j]=v[j+1];
                v[j+1]=tmp;
            }
        }
    }
}

int length(vector<string> v){
    vector<string> t;
    t=v;
    vsort(t);
    if(t==v)
        return 1;
    else
        return 0;

}

int main(int argc, char const *argv[])
{
    int n;
    while(cin>>n&&n<=100){
        vector<string> v1;
        for (int i = 0; i < n; ++i)
        {
            string tmp;
            cin>>tmp;
            v1.push_back(tmp);
        }
        if(dictsort(v1)){
            if(length(v1))
                cout<<"both"<<endl;
            else
                cout<<"lexicographically"<<endl;
        }
        else{
            if(length(v1))
                cout<<"lengths"<<endl;
            else
                cout<<"none"<<endl;
        }

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Hay54/article/details/82178334