easy
- 模拟求解,按照题目要求拆分
- 遍历每个字符,判断类型,放入对应数组中
/**
* @param {string} s
* @return {string}
*/
var reformat = function(s) {
let digits = [], chars = [];
for(let i=0;i<s.length;i++){
if('0'.charCodeAt(0)<=s[i].charCodeAt(0)&&s[i].charCodeAt(0)<='9'.charCodeAt(0)){
digits.push(s[i])
}else{
chars.push(s[i])
}
}
if(Math.abs(digits.length-chars.length)>1){
return ''
}else{
if(digits.length>chars.length){
let res = ''
digits.forEach((d,index)=> {
res += `${d}${chars[index]}`
})
return res.replace(/undefined/g,'');
}else{
let res = ''
chars.forEach((d,index)=> {
res += `${d}${digits[index]}`
})
return res.replace(/undefined/g,'');
}
}
};
console.log(reformat('ab123'))
console.log(reformat('covid2019'))
console.log(reformat('leetcode'))
console.log(reformat('a0b1c2'))
console.log(reformat('a0b1'))
console.log(reformat('1111111112222222222'))
console.log(reformat('a1c2aa'))
执行结果:通过
执行用时:80 ms, 在所有 JavaScript 提交中击败了30.53%的用户
内存消耗:45 MB, 在所有 JavaScript 提交中击败了66.32%的用户
通过测试用例:302 / 302