LeetCode387 字符串中的第一个唯一字符 & 剑指Offer 50 第一个只出现一次的字符

这篇博客主要介绍了LeetCode387题和剑指Offer50题,即找到字符串中第一个唯一字符的问题。博主提供了三种解法,包括使用哈希表存储字符频数和索引,以及利用队列来实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode387 字符串中的第一个唯一字符 & 剑指Offer 50 第一个只出现一次的字符

题目

LeetCode387 字符串中的第一个唯一字符:
在这里插入图片描述
剑指Offer 50 第一个只出现一次的字符:
在这里插入图片描述
387题返回的是字符,剑指Offer 50返回的是索引。

解题

解题一:使用哈希表存储频数

在这里插入图片描述
剑指Offer 50 第一个只出现一次的字符:

// javascript
var firstUniqChar = function(s) {
    const frequency = _.countBy(s);
    for (const [i, ch] of Array.from(s).entries()) {
        if (frequency[ch] === 1) {
            return ch;
        }
    }
    return ' ';
};

LeetCode387 字符串中的第一个唯一字符:

// javascript
var firstUniqChar = function(s) {
    const frequency = _.countBy(s);
    for (const [i, ch] of Array.from(s).entries()) {
        if (frequency[ch] === 1) {
            return i;
        }
    }
    return -1;
};

在这里插入图片描述

解题二:使用哈希表存储索引

在这里插入图片描述

// javascript
var firstUniqChar = function(s) {
    const n = s.length;
    const position = new Map();
    for (const [i, ch] of Array.from(s).entries()) {
        if (position.has(ch)) {
            position.set(ch, -1);
        } else {
            position.set(ch, i);
        }
    }
    let first = n;
    for (const pos of position.values()) {
        if (pos !== -1 && pos < first) {
            first = pos;
        }
    }
    return first === n ? ' ' : s[first];
    // return first === n ? -1 : first;// 387题返回值
};

在这里插入图片描述

解题三:队列

在这里插入图片描述

// javascript
var firstUniqChar = function(s) {
    const position = new Map();
    const queue = [];
    for (const [i, ch] of Array.from(s).entries()) {
        if (!position.has(ch)) {
            position.set(ch, i);
            queue.push([ch, i]);           
        } else {
            position.set(ch, -1);
            while (queue.length > 0 && position.get(queue[0][0]) === -1) {
                queue.shift();
            }
        }
    }
    return queue.length > 0 ? queue[0][0] : ' ';
    // return queue.length > 0 ? queue[0][1] : -1;  // 387题返回值
};

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值