#include
#include
#include
using namespace std;
bool isSubstring(string a,string b,int l){
string r=b.substr(0,l);
if(r==a){
return true;
}
else{
return false;
}
}
int main() {
string s[10];
int n;
cin>>n;
for(int i=0;i<n; i++)
cin>>s[i];
sort(s, s+n);
for(int i=0;i<n-1;i++){
string a=s[i];
string b=s[i+1];
int l=a.length();
if(isSubstring(a,b,l)){
swap(s[i],s[i+1]);
}
}
for(int i=0;i<n; i++){
cout<<s[i]<<" ";
}
return 0;
}
I have first sorted simply, which would give a lexicographically array.
And then I have compared consecutive elements and if one is a substring of the other then I have swapped them.
Please let me know what is wrong with the approach/implementation .