2020年美团秋招2道编程题

1 题目大意:对于输入的字符串逆序排序后输出,空格排在最前面。不能使用既有排序算法,如sort。


#include
#include
#include

using namespace std;

void swap(string & a, string & b)
{
    string tmp = a;
    a = b;
    b = tmp;
}

void Qsort(vector & seq, int beg, int end)
{
    string tmp = seq[beg];
    if (beg >= end)
    {
        return;
    }
    int i = beg, j = end;
    while (i != j)
    {
        while (j > i && seq[j] >= tmp)
        {
            j--;
        }
        swap(seq[i], seq[j]);
        while (j > i && seq[i] <= tmp)
        {
            i++;
        }
        swap(seq[i], seq[j]);
    }
    Qsort(seq, beg, i - 1);
    Qsort(seq, i + 1, end);
}

int main()
{
    string in{};
    cin >> in;
    vector seq{};
    string tmp{};
    for (int i = 0; i < in.size(); i++)
    {
        if (in[i] != ',')
        {
            tmp += in[i];
        }
        else
        {
            seq.push_back(tmp);
            tmp = "";
        }
    }
    seq.push_back(tmp);
    for (int i = seq.size() - 1; i > 1; i++)
    {
        cout << seq[i] << ",";
    }
    cout << seq[0] << endl;
    return 0;
}

2 题目大意:寻找最长公共前缀。

#include
#include
#include


using namespace std;

string LCP(vector & strs)
{
    if (strs.empty()) return "";
    string res = "";
    for (int j = 0; j < strs[0].size(); ++j)
    {
        char c = strs[0][j];
        for (int i= 1; i < strs.size(); ++i)
        {
            if (j >= strs[i].size() || strs[i][j] != c)
            {
                return res;
            }
        }
        res.push_back(c);
    }
    return res;


}

int main()
{
    int n_str{};
    cin >> n_str;
    vector strs;
    for (int i = 0; i < n_str; i++)
    {
        string tmp{};
        cin >> tmp;
        if (tmp != " ")
        strs.push_back(tmp);
    }

    while (true)
    {
        vector tmp_strs;
        int a{}, b{};
        cin >> a >> b;
        if ((a < 1 || a > n_str) && (b < 1 || b > n_str)) break;
        tmp_strs.push_back(strs[a - 1]);
        tmp_strs.push_back(strs[b - 1]);
        string res = LCP(tmp_strs);
        cout << res.size() << endl;
    }
    return 0;
}

你可能感兴趣的:(C++)