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

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

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)
})
全部评论

相关推荐

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