Skip to content

Commit e0b40b3

Browse files
authored
String Sort Solution Added
1 parent c88838d commit e0b40b3

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

Hacker Blocks/String Sort.cpp

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/* Hacker Blocks */
2+
/* Title - String Sort */
3+
/* Created By - Akash Modak */
4+
/* Date - 28/06/2020 */
5+
6+
// Nishant is a very naughty boy in Launchpad Batch. One day he was playing with strings, and randomly shuffled them all. Your task is to help Nishant Sort all the strings ( lexicographically ) but if a string is present completely as a prefix in another string, then string with longer length should come first. Eg bat, batman are 2 strings and the string bat is present as a prefix in Batman - then sorted order should have - Batman, bat.
7+
8+
// Input Format
9+
// N(integer) followed by N strings.
10+
11+
// Constraints
12+
// N<=1000
13+
14+
// Output Format
15+
// N lines each containing one string.
16+
17+
// Sample Input
18+
// 3
19+
// bat
20+
// apple
21+
// batman
22+
// Sample Output
23+
// apple
24+
// batman
25+
// bat
26+
// Explanation
27+
// In mathematics, the lexicographic or lexicographical order (also known as lexical order, dictionary order, alphabetical order or lexicographic(al) product) is a generalization of the way words are alphabetically ordered based on the alphabetical order of their component letters.
28+
29+
#include<iostream>
30+
#include<string>
31+
#include<algorithm>
32+
using namespace std;
33+
bool compare(string a,string b){
34+
int n = a.length();
35+
int m = b.length();
36+
int len = min(n,m);
37+
int i = 0;
38+
// cout<<a<<a.length()<<" "<<b<<b.length()<<endl;
39+
40+
while(a[i]==b[i] && i<len){
41+
42+
i++;
43+
}
44+
if(i==len){
45+
// cout<<a<<a.length()<<" "<<b<<b.length()<<endl;
46+
return a.length()>b.length();
47+
}
48+
else
49+
return a.compare(b)<0?true:false;
50+
}
51+
int main() {
52+
int n;
53+
cin>>n;
54+
string a[n];
55+
for(int i=0;i<n;i++)
56+
cin>>a[i];
57+
sort(a,a+n,compare);
58+
for(int i=0;i<n;i++){
59+
cout<<a[i]<<endl;
60+
}
61+
return 0;
62+
}

0 commit comments

Comments
 (0)