Leecode: Reorganize String(JS解答)
解题思路:
先用一个数组统计每个字母出现的次数,查看出现次数最高字母的次数,如果次数大于字符串长度的一半,则直接返回空字符串结果,因为不存在符合条件的答案
下一步,先把出现次数最多的字母填在结果集的偶数位,填完之后选择下一字母继续填在后面的偶数位,如果超出字符串长度,则开始填奇数位
上代码:
function reorganizeString(S: string): string {
let count:number[] = new Array(26).fill(0);
for(let i = 0; i < S.length; i++){
let index = S.charAt(i).charCodeAt(0) - "a".charCodeAt(0);
count[index]++
}
let maxIndex = 0;
for(let i = 0; i < count.length; i++){
if(count[i] > count[maxIndex]){
maxIndex = i;
}
}
console.log(count)
if(count[maxIndex] > (S.length+1)/2){
return ""
}
let res:string[] = new Array(S.length);
let start = 0;
while (count[maxIndex] > 0){
res[start] = String.fromCharCode(maxIndex + "a".charCodeAt(0));
start += 2;
count[maxIndex]--;
}
for(let i = 0; i < count.length; i++){
while (count[i] > 0){
if(start > S.length-1){ //偶数位用完,开始奇数位
start = 1;
}
res[start] = String.fromCharCode(i + "a".charCodeAt(0));
start += 2;
count[i]--;
}
}
return res.join("");
};