【算法】字符串:字符串中的第一个唯一字符

73 阅读1分钟

题目:字符串中的第一个唯一字符

leetcode链接:字符串中的第一个唯一字符

说明:给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。

理解:

1、找到给定字符串第一个不重复的字符

2、返回该字符的索引

3、如果没有这样的字符,则索引返回-1

思路:

1、利用lodash统计字符出现的频率,只出现一次的即为要找的字符,并返回其索引。

2、利用Map存储索引,重复的为-1,不重复则为具体索引

题解:

方案一:统计字符出现的频率

/**
 * @param {string} s
 * @return {number}
 */
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;
};

image.png

方案二、利用Map存储索引

/**
 * @param {string} s
 * @return {number}
 */
var firstUniqChar = function(s) {
    const position = new Map();
    const n = s.length;
    for (let [i, ch] of Array.from(s).entries()) {
        if (position.has(ch)) {
            position.set(ch, -1);
        } else {
            position.set(ch, i);
        }
    }
    let first = n;
    for (let pos of position.values()) {
        if (pos !== -1 && pos < first) {
            first = pos;
        }
    }
    if (first === n) {
        first = -1;
    }
    return first;
};

image.png

总结:

本篇提供两种查找字符串中的第一个唯一字符的实现,不过看起来效率都不大高的样子~