【python】【leetcode】【算法题目387—First Unique Character in a String】

来源:互联网 发布:外国人在中国翻译软件 编辑:程序博客网 时间:2024/05/29 09:35

一、题目描述

题目原文:

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

(输入一个字符串,给出此串中非重复的字符,并返回其下标,若不存在则返回-1)

二、题目分析

思路:依次循环,判断当前字符在该串中出现的的次数,若为1则输出即可。

(用have_done列表存放已经判断过的元素,避免重复判断,用于优化时间)

三、Python代码

class Solution(object):    def firstUniqChar(self, s):        """        :type s: str        :rtype: int        """        have_done = []        for i in range(0, len(s)):            if s[i] not in have_done:                if s.count(s[i]) == 1:                    return i                else:                    have_done.append(s[i])            else:                continue        return -1

四、其他

题目链接:https://leetcode.com/problems/first-unique-character-in-a-string/

Runtime: 228 ms

想法不够优化,欢迎大家留言交流~

0 0
原创粉丝点击