题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/5af18ba2eb45443aa91a11e848aa6723
注释是GPT-4写的, 我懒得写了, 为了锻炼代码水平用了自定义排序列的知识, 其实写完了还是有点没理解, 欢迎各位大佬来评论.
#include <iostream> #include <string> #include <deque> #include <algorithm> using namespace std; // 自定义排序类,根据字符串首字母排序(不区分大小写) class sortAlgorithmByFirstLetter { public: bool operator()(string v1, string v2) { int i, k; // 确定比较长度,取较短字符串长度 if(v1.length() >= v2.length()){ k = v2.length(); } else { k = v1.length(); } // 遍历字符串,逐字符比较 for (i = 0; i < k; i++) { // 如果 v1[i] 是大写字母,转换为小写字母 if (v1[i] <= 'Z') { v1[i] += 'a' - 'A'; } // 如果 v2[i] 是大写字母,转换为小写字母 else if (v2[i] <= 'Z') { v2[i] += 'a' - 'A'; } // 比较字符,确定排序顺序 if(v1[i] > v2[i]) { return 0; } else if(v1[i] < v2[i]) { return 1; } else { // 如果字符相等,继续比较下一个字符 } } // 如果比较长度相等,返回 false(即不需要交换顺序) if(v1.length() >= v2.length()){ return 0; } else { // 否则返回 true(需要交换顺序) return 1; } } }; int main() { int n; deque<string> tempDeque; string tempStr; cin >> n; // 读取输入的字符串并添加到队列中 for (int i = 0; i < n; i++) { cin >> tempStr; tempDeque.push_back(tempStr); } // 使用自定义排序类对字符串进行排序 sort(tempDeque.begin(), tempDeque.end(), sortAlgorithmByFirstLetter()); // 输出排序后的字符串 for (deque<string>::iterator it = tempDeque.begin(); it != tempDeque.end(); it++) { cout << *it << endl; } }