387.字符串中的第一个唯一字符
给定一个字符串 s ,找到 它的第一个不重复的字符,并返回它的索引 。如果不存在,则返回 -1 。
示例 1:
输入: s = "leetcode"
输出: 0
示例 2:
输入: s = "loveleetcode"
输出: 2
示例 3:
输入: s = "aabb"
输出: -1
提示:
1 <= s.length <= 105
s 只包含小写字母
方法一:使用哈希表存储频数
时间复杂度:O(n),其中 n是字符串 s的长度。我们需要进行两次遍历。
空间复杂度:O(∣Σ∣),其中 Σ 是字符集,在本题中 s只包含小写字母,因此 ∣Σ∣≤26。我们需要O(∣Σ∣) 的空间存储哈希映射。
1 /** 2 * @param {string} s 3 * @return {number} 4 */ 5 var firstUniqChar = function(s) { 6 const frequency = _.countBy(s); 7 for (const [i, ch] of Array.from(s).entries()) { 8 if (frequency[ch] === 1) { 9 return i; 10 } 11 } 12 return -1; 13 };

浙公网安备 33010602011771号