34.第一次只出现一次的字符(python)

题目描述

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
 
两次遍历,第一次存放字符计数
第二次查找当前字符是否出现一次
时间复杂度 O(N)  空间复杂度O(N)   用count函数只需要一次遍历,空间复杂度O(1)
 1 # -*- coding:utf-8 -*-
 2 class Solution:
 3     def FirstNotRepeatingChar(self, s):
 4         # write code here
 5         word_dic={}
 6         for i in range(len(s)):
 7             if s[i] not in word_dic:
 8                 word_dic[s[i]]=1
 9             else:
10                 word_dic[s[i]]+=1
11         for i in range(len(s)):
12             if word_dic[s[i]]==1:
13                 return i
14         return -1

2019-12-23 15:25:15

posted @ 2019-12-23 15:26  Assange  阅读(421)  评论(0编辑  收藏  举报