对字符串中的所有字符进行排序

时间:2017-08-19 23:37:13

标签: javascript arrays string algorithm sorting

我正在尝试解决这个问题,我想在字符串中对字符数组进行排序

问题:

对字符数组进行排序(仅限ASCII,不是UTF8)。

输入:一个字符串,如完整的英文句子,由换行符或NULL分隔。重复是可以的。

例如:这很容易

输出:字符串,按其ASCII值的排序顺序排列。您可以覆盖现有阵列。

例如:Taehiisssy

解决方案复杂性:目标是线性时间和常量额外空间。

我知道在JavaScript中你可以做类似

的事情
const sorted = str.split('').sort().join('')
编辑:如果我能从中获取任何东西,我正试图看看我是否可以使用charCodeAt(i)方法。

但这将是O(nLogN)^^不是线性的(+额外空间O(N)用于分割)

但是在恒定的空间中,我们如何对字符数组进行排序?

1 个答案:

答案 0 :(得分:2)

逐字符制定累积计数

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, e.g. "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);

这只使用一个常量表大小,256个数字长(或者你希望允许的任何数量的不同符号)。

它所花费的时间与输入字符串中的字符数呈线性关系(假设当该字符的计数为零时,内部FOR循环几乎没有花费时间)。