leetcode with python:387. First Unique Character in a String

题目:

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

给定一字串,找出第一个独一无二的值,回传它的index,若不存在则回传-1

这题我选择使用hash set

class Solution:    def firstUniqChar(self, s: str) -> int:        s1=set()                for i in range(len(s)):            if s[i] not in s1:                if s[i] not in s[i+1:len(s)]:                    return i                else:                    s1.add(s[i])                    return -1

将字串里的字元一一确认
若在此字元之后的字串不存在此字元,回传该字元index
检测过的字元会放入集合s1,下次遇到相同字元就不进行检测
若都无回传,则回传-1
最后执行时间51ms(faster than 99.88%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章