Leetcode 387. First Unique Character in a String

Problem

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Algorithm

Use two lists: one list is used to count the letters in “s”; the other list is the position where the letter first appears. Then find the smallest position of the letters appear once.

Code

class Solution:
    def firstUniqChar(self, s: str) -> int:
        sCnts = [0] * 26
        sStart = [0] * 26
        cnts = 0
        for c in s:
            sCnts[ord(c) - ord('a')] += 1
            if sCnts[ord(c) - ord('a')] == 1:
                sStart[ord(c) - ord('a')] = cnts
            cnts += 1
        
        index = -1
        for i in range(26):
            if sCnts[i] == 1 and (index < 0 or index > sStart[i]):
                index = sStart[i]
        
        return index

相关推荐

  1. Leetcode 377 组合总和 Ⅳ

    2024-03-18 12:04:01       47 阅读
  2. Leetcode 337 打家劫舍 III

    2024-03-18 12:04:01       42 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-18 12:04:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-18 12:04:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-18 12:04:01       87 阅读
  4. Python语言-面向对象

    2024-03-18 12:04:01       96 阅读

热门阅读

  1. GitLab 中国用户如何免费获取本土化服务?

    2024-03-18 12:04:01       38 阅读
  2. C语言经典面试题目(十八)

    2024-03-18 12:04:01       41 阅读
  3. milvus-standalone启动失败unhealthy

    2024-03-18 12:04:01       43 阅读
  4. Github基本功能和使用技巧

    2024-03-18 12:04:01       42 阅读
  5. 128天创作纪念日

    2024-03-18 12:04:01       40 阅读
  6. 项目四 完成学生信息的持久化存储

    2024-03-18 12:04:01       45 阅读
  7. vue框架渲染原理

    2024-03-18 12:04:01       40 阅读
  8. spring——BeanFactory与ApplicationContext接口、bean标签

    2024-03-18 12:04:01       43 阅读
  9. 前端小白的学习之路(事件流)

    2024-03-18 12:04:01       35 阅读
  10. 2024/03/16----面试中遇到的一些面试题

    2024-03-18 12:04:01       41 阅读
  11. 【Python】Flask上下文管理

    2024-03-18 12:04:01       44 阅读
  12. sparksql的SQL风格编程

    2024-03-18 12:04:01       44 阅读