美文网首页LeetCode
字符串中的第一个唯一字符

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

作者: Billsion | 来源:发表于2022-02-19 14:13 被阅读0次

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

例子:
s = "leetcode" , 返回 0

s = "loveleetcode", 返回 2

代码:

private fun  firstUniqChar(s:String) : Int {
        if (s.isEmpty()) return -1
        val map = HashMap<Char, Int>()
        for (i in 0 until s.length) {
            val c = s[i]
            map[c] = map.getOrDefault(c, 0) + 1
        }
        for (i in 0 until s.length) {
            // 如果从1开始数,就加一,否则返回i
            if (map[s[i]] == 1) return i + 1
        }
        return -1
    }

相关文章

网友评论

    本文标题:字符串中的第一个唯一字符

    本文链接:https://www.haomeiwen.com/subject/lqerlrtx.html