碰到一题求字典序的,自己写了很多行,还总是错,用了指针各种之类的不兼容。代码如下
#include<bits/stdc++.h>
#define ll long long
using namespace std;
char s2[1005][26];
bool com(char s[],char t[]) {
int i=0;
for(; s[i]!='.'&&t[i]!='.'; i++) {
if(s[i]>=97&&t[i]>=97) {
if(s[i]>t[i]) {
return 1;
} else if(s[i]==t[i]) {
continue;
} else {
return 0;
}
}else if(s[i]<=91&&t[i]<=91)
{
if(s[i]>t[i]) {
return 1;
} else if(s[i]==t[i]) {
continue;
} else {
return 0;
}
}
else if(s[i]<=91)
{
return 0;
}
else
{
return 1;
}
}
if(t[i]=='.') {
return 1;
} else {
return 0;
}
}
int main() {
int n;
// s=(char **)malloc(sizeof(char)*1005*26);
char s1[26];
cin>>n;
for(int i=0; i<n; i++) {
scanf("%s",&s1);
int k=strlen(s1);
for(int j=k; j<=25; j++) {
s1[j]='.';
}
for(int x=0; x<=25; x++) {
s2[i][x]=s1[x];
}
}
// for(int i=0;i<n;i++)
// {
// for(int j=0;j<=25;j++)
// {
// if(s[i][j]=='.')
// {
// break;
// }
// else
// {
// printf("%c",s[i][j]);
// }
// }
if(s[i]=='.')
break;
printf("%s",s[i]);
// cout<<endl;
// }
for(int i=0; i<n; i++) {
for(int j=i+1; j<n; j++) {
if(com(s2[i],s2[j])) {
//cout<<'1'<<endl;
char x[26];
for(int m=0; m<=25; m++) {
x[m]=s2[i][m];
s2[i][m]=s2[j][m];
s2[j][m]=x[m];
}
}
// cout<<"fg ";
}
}
for(int i=0; i<n; i++) {
for(int j=0; j<=25; j++) {
if(s2[i][j]=='.') {
break;
} else {
printf("%c",s2[i][j]);
}
}
// if(s[i]=='.')
// break;
// printf("%s",s[i]);
cout<<endl;
}
}
看了题解之后,发现有string 加上sort做起来好简单,于是有:
#include<bits/stdc++.h>
using namespace std;
bool cmp(string a,string b) {
//return a.compare(b)<0; //升序
return a<b; //两个效果一样,A>a,大写大于小写
}
int main() {
int n;
string str[1001];
cin>>n;
for(int i=0; i<n; i++) {
cin>>str[i];
}
sort(str,str+n,cmp);
for(int i=0; i<n; i++) {
cout<<str[i]<<endl;
}
return 0;
}