题解 | #找出字符串中第一个只出现一次的字符#

找出字符串中第一个只出现一次的字符

http://www.nowcoder.com/practice/e896d0f82f1246a3aa7b232ce38029d4

// 用对象存储字符串中字符出现的次数和字符的索引

数据结构的形式为 {key: []}

aabb 转换为  => 
{
 a: [2, 0],   // 第一个2表示a出现了2次,第二个0表示第一个a的索引为0
 b: [2, 2]    // 第一个2表示b出现了2次,第二个2表示第一个b的索引为2
}
const readline = require('readline')
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
})

rl.on('line', function(line){
    const obj = {}
    for(let i=0; i<line.length; i++){
        const char = line[i]
        if(obj[char] && obj[char][0] > 0){
            obj[char][0] = obj[char][0] + 1
        }else{
            obj[char] = [1, i]
        }
    }
    let max = line.length, result = ''
    for(let key in obj){
        if(obj[key][0] === 1 && obj[key][1] < max){
            max = obj[key][1]
            result = key
        }
    }
    result = result == '' ? '-1' : result
    console.log(result)
})
全部评论

相关推荐

05-01 22:41
中南大学 Java
点赞 评论 收藏
分享
05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务