美团笔试题-字符串的分割与排序
1.题目
生活中经常有需要将多个字符串进行排序的需要,比如将美团点评的部分业务名称(外卖、打车、旅游、丽人、美食、结婚、旅游景点、教培、门票、酒店),用拼音表示之后按字母逆序排序。字母逆序指从z到a排序,比如对两个字符串排序时,先比较第一个字母按字母逆序排z在a的前面,当第一个字母一样时再比较第二个字母按字母逆序排,以此类推。特殊情况1)空字符串需排在最前面;2)若一个短字符串是另一个长字符串的前缀则短字符串排在前面。请自行实现代码进行排序,直接调用sort等排序方法将不得分且视为作弊。
输入描述:
输入为一行,由多个字符串以英文逗号拼接而成,最多不超过128个字符串且可能有重复。每个字符串由小写字母a-z组成,可以为空,最长不超过128个字符。
输出描述:
输出一行,为排序之后的字符串,用逗号隔开
2.AC代码
#include<iostream>
#include<string>
#include<vector>
#include<algorithm> using namespace std;
//定义一个结构题,重写<运行赋
struct item{
string name;
item(string n) {
name = n;
}
bool operator <(const item &a)const { //此处严格对应题目的排序要求
int len = name.length() < a.name.length() ? name.length() : a.name.length();
int i = 0;
while(i < len) {
if(name[i] - a.name[i] > 0)
return true;
else if(name[i] - a.name[i] < 0)
return false;
else
i++;
}
if(name.length() < a.name.length())
return true;
return false;
}
};
//将字符串line根据字符c分割开
vector<string> strSplit(string line,char c) {
vector<string> strArr;
string temp = "";
int i = 0;
while (i < line.length()) {
if (line[i] - c == 0) {
strArr.push_back(temp);
temp = "";
}
else
temp = temp + line[i];
i++;
}
if(temp.length() > 0)
strArr.push_back(temp);
return strArr;
}
//冒泡排序
void bubbleSort(vector<item> &mItem) {
int len = mItem.size();
for(int i = 1;i < len;i++) {
for(int j = 0;j < len - i;j++) {
if(mItem[j + 1] < mItem[j]) { //结构体中重写<操作符的目的
string temp = mItem[j].name;
mItem[j].name = mItem[j + 1].name;
mItem[j + 1].name = temp;
}
}
}
}
int main() {
vector<string> strArr;
vector<string> tmpArr;
while(true) { //可以输入多行字符串
string line;
cin >> line;
if(line.size() == 0)
break;
if(line[0] - 'a' >= 0 || 'z' - line[0] >= 0 ) {
tmpArr = strSplit(line,',');
strArr.insert(strArr.begin(),tmpArr.begin(),tmpArr.end());
}
}
vector<item> mItem;
for(int i = 0;i < strArr.size();i++) {
item indiv(strArr[i]);
mItem.push_back(indiv);
}
bubbleSort(mItem);
for(int i = 0;i < mItem.size();i++) {
cout << mItem[i].name;
if(i < mItem.size() - 1)
cout << ",";
}
return 0;
}
3.简要介绍
1)本文首先对多行字符串根据字条c进行分割,返回vector类型的数据
2)然后通过将字符构造成个体,通过构造体中重写<运算符,来比较结构体对象的大小;
3)由于题目不准用内置的排序函数,本文采用自定义的冒泡排序法排序;
本文详细解析了一道美团的笔试题,题目要求对一组特定的业务名称进行拼音表示并按字母逆序排序,同时考虑了空字符串和前缀匹配的特殊规则。文章提供了AC代码,包括字符串分割、自定义结构体比较和冒泡排序算法的实现。
2833

被折叠的 条评论
为什么被折叠?



