简体   繁体   中英

Sort all characters in a string

I'm trying to solve this problem where I want to sort array of characters in a string

Problem:

Sort an array of characters (ASCII only, not UTF8).

Input: A string of characters, like a full English sentence, delimited by a newline or NULL. Duplicates are okay.

eg: This is easy

Output: A string of characters, in sorted order of their ASCII values. You can overwrite the existing array.

eg: Taehiisssy

Solution Complexity: Aim for linear time and constant additional space.

I know that in JavaScript you can do something like

const sorted = str.split('').sort().join('')

EDIT: I'm trying to see if I can make use of charCodeAt(i) method if I can get anything out of it.

But this would be O(nLogN) ^^ not linear (+extra space O(N) for split)

But in constant space, how would we sort array of characters?

Character-by-character formulate a cumulative count

 const s="This is easy"; // Create an array which will hold the counts of each character, from 0 to 255 (although strictly speaking ASCII is only up to 127) let count = Array(256).fill(0); // Look at each character in the input and increment the count for that character in the array. for(let i=0; i<= s.length; i++) { c=s.charCodeAt(i); count[c]++; } let out=""; // Now scan through the character count array ... for(let i=0; i<= 255; i++) { // And for each character, eg "T", show it the number of times you saw it in the input for(let rep=0; rep<count[i]; rep++){ out+=String.fromCharCode(i); } } console.log(out); 

This only uses a constant table size, 256 numbers long (or whatever number of different symbols you wish to allow).

And the time it takes is linearly dependent on the number of characters in the input string (assuming almost no time is spent on the inner FOR loop when the count is zero for that character).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM