题解 | 字符串排序

字符串排序

https://www.nowcoder.com/practice/9ad2f07d6eb74a6e935e54279b29910d

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

struct word {
    string s;
};

vector<int> customRank(26);  // 修改变量名

bool compare(const word& a, const word& b) {
    const string& s = a.s;
    const string& t = b.s;

    int lens = s.size();
    int lent = t.size();
    int minlen = min(lens, lent);

    for (int i = 0; i < minlen; i++) {
        int ranks = customRank[s[i] - 'a']; 
        int rankt = customRank[t[i] - 'a']; 

        if (ranks != rankt) {
            return ranks < rankt;
        }
    }
    return lens < lent;
}

int main() {
    string s2;
    cin >> s2;
    for (int i = 0; i < 26; i++) {
        customRank[s2[i] - 'a'] = i; 
    }
    int n;
    cin >> n;

    vector<word> words(n);
    for (int i = 0; i < n; i++) {
        cin >> words[i].s;
    }
    sort(words.begin(), words.end(), compare);

    for (const auto& word : words) {
        cout << word.s << endl;
    }
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务