Reputation: 23
i am new in programming. i just learned strings in c++.
I have N strings and I want to sort them in lexicographical order.(Dictionary order)
How, can i do that as N is quite Big 1 <= N <= 1e5
and size of each string is 1 <= |s| <= 1000
.
Also the string is only made of small English alphabets.
I have figured out one method which is sorting them but test cases are tight and giving TLE.
Is there a better Approach for this problem. Please help.
Upvotes: 2
Views: 8029
Reputation: 157
Yes, there are two ways.
HASHING
.HOW TO USE ?
'a'
occurred in string then hash[0] = hash[0] + 1;
i
print all characters until hash[i]
becomes zero. It is because, as you want to sort string lexicographically the best way is print all 'a' then all 'b' and so on present in string
.O(n*2s)
.int hash[26]={0};
for( int i = 0 ; i < s.length() ; i++ ) // s.length() returns string length
{
hash[s[i]-97] += 1; // s[i] - 97 actually returns index for the character
}
char ch;
for( int i = 0 ; i < 26 ; i++ )
{
ch = i+97; // making the character required
while(hash[i]) { cout << ch; hash[i] -= 1; } // printing it its frequency times
}
nlog(n) sorting
HOW ?
sort( s.begin() , s.end() ) ;
string s;
cin >> s;
sort( s.begin(); s.end() );
cout << s << endl;
Upvotes: 2