leetcode icon indicating copy to clipboard operation
leetcode copied to clipboard

387. 字符串中的第一个唯一字符

Open buuing opened this issue 4 years ago • 0 comments

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

示例:

s = "leetcode"
返回 0

s = "loveleetcode"
返回 2

提示:你可以假定该字符串只包含小写字母。


来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/first-unique-character-in-a-string 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。




  • 哈希表 (常规解法)
const firstUniqChar = s => {
  let map = new Map()
  for (let i = 0; i < s.length; i++) {
    let curr = s[i]
    if (map.has(curr)) {
      map.set(curr, -1)
    } else {
      map.set(curr, i)
    }
  }
  for (let key of map.keys()) {
    let curr = map.get(key)
    if (curr !== -1) return curr
  }
  return -1
}

  • 如果是抛开时间复杂度来看, 这道题有一个很有趣的解法, 那就是利用indexOflastIndexOf判断, 如果两个值相等, 就可以认为该字符只出现过一次
const firstUniqChar = s => {
  for (let i = 0; i < s.length; i++) {
    let curr = s[i]
    if (s.indexOf(curr) === s.lastIndexOf(curr)) {
      return i
    }
  }
  return -1
}

buuing avatar Dec 23 '20 03:12 buuing