题解 | #字符串排序#

字符串排序

http://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584

while(line = readline()) {
    let length = line.length;
    let pointer = 97;
    let codeArr = [];
    let otherArr = [];
    for (let i = 0; i < length; i++) {
        let code = line.charCodeAt(i);
        if (!isABC(code)){
            otherArr.push({index: i, str: line[i]});
        }
    }
    //逻辑麻烦就在这,这里参考别人的代码,他的想法很简单就是把字母按照a-z的顺序拿出来,然后把原有的替换。
  //我的逻辑是把字母拿出来然后都大写用unicode排序,再还原,结果不知道为啥sort排序把相同code的index搞乱了,剩下就是把非字母的位置记录然后插入
    for (let i = 0; i < 26; i++) {
        for (let j = 0; j < length; j++ ) {
            let code = line.charCodeAt(j);
            if (isABC(code) && line[j].toLowerCase().charCodeAt() === pointer) {
                codeArr.push(line[j]);
            }
        }
        pointer++;
    }
 
    function isABC(code) {
        if (code >= 65 && code <= 90 || code >=97 && code <= 122) {
            return true;
        }
        return false;
    }
    
    for (let item of otherArr) {
        codeArr.splice(item.index,0, item.str)
    }
    
   console.log(codeArr.join(''))
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务