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

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

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

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', function (line) {
    if(line){
        // console.log(handleFunc1(line))
        console.log(handleFunc2(line))
    }
});

// 方法1
function handleFunc1(str){
    const obj = {}
    // 计算所有字符出现的次数
    for(let key of str){
        if(obj[key]){
            obj[key]++
        }else {
            obj[key] = 1
        }
    }

    // 获取对象的键
    const keys = Object.keys(obj)
    // 获取对象的值
    const values = Object.values(obj)
    // 找到出现次数为1的
    const index = values.indexOf(1)
    if( index === -1 ){
        return -1
    }else {
        return keys[index]
    }
}

// 方法2--更简单
function handleFunc2(str) {
    for(let key of str){
        // 当从左找与从右找找到的下标相等时,证明该字符只出现一次
        if(str.indexOf(key) === str.lastIndexOf(key)){
            return key
        }
    }
    return -1
}

全部评论

相关推荐

11-13 14:37
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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