leetcode_387. First Unique Character in a String 找第一个非重复的字符下标,python字典的应用
2016-10-16 16:34
471 查看
题目:
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
Note: You may assume the string contain only lowercase letters.
题意:
给定一个字符串,写一个函数找到这个字符串中第一个非重复字符出现的下标。
代码:
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
dict_num = dict()
for x in s :
dict_num[x] = 0
for x in s :
dict_num[x] = dict_num[x] + 1 #存储各字符出现的次数
for i in range(len(s)) : #在s中遍历,判断当前字符出现次数是否为1
if dict_num[s[i]] == 1 :
return i
return -1
笔记:
用字典dict_num存储字符串s中各字符出现的次数,其中dict_num中各key值是按照字母在字典中的顺序存储的。
即假设s='leetcode',其对应的dict_num的内容如下:
可见最后在判断s中第一个不重复的字符时,不能在dict_num中遍历,因为dict_num中第一个value值为1的字符在s中可能并不是第一个。 故应该在s中遍历,判断当前字符在dict_num中value是否为1.
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode" return 0. s = "loveleetcode", return 2.
Note: You may assume the string contain only lowercase letters.
题意:
给定一个字符串,写一个函数找到这个字符串中第一个非重复字符出现的下标。
代码:
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
dict_num = dict()
for x in s :
dict_num[x] = 0
for x in s :
dict_num[x] = dict_num[x] + 1 #存储各字符出现的次数
for i in range(len(s)) : #在s中遍历,判断当前字符出现次数是否为1
if dict_num[s[i]] == 1 :
return i
return -1
笔记:
用字典dict_num存储字符串s中各字符出现的次数,其中dict_num中各key值是按照字母在字典中的顺序存储的。
即假设s='leetcode',其对应的dict_num的内容如下:
{u'c': 1, u'e': 3, u'd': 1, u'l': 1, u'o': 1, u't': 1}
可见最后在判断s中第一个不重复的字符时,不能在dict_num中遍历,因为dict_num中第一个value值为1的字符在s中可能并不是第一个。 故应该在s中遍历,判断当前字符在dict_num中value是否为1.
相关文章推荐
- leetcode—242. Valid Anagram 判断由颠倒字母顺序而构成的词,python字典的应用
- [LeetCode] First Unique Character in a String 寻找第一个不重复出现的字符
- leetcode-1:python基础,循环、条件、列表、字典的应用,enumerate、range函数以及2.0和3.0print的区别
- 返回字符串中第一个不重复字符的下标 下标从0开始
- Leetcode 刷题(python)之 无重复字符的最长子串
- Python :字符流中第一个不重复的字符
- 16、JAVA 找出一个字符串中,第一个重复出现的字符
- 第一次看到不是用字典而是用内容的第一个字符来表示静态数据的。
- 字符串查找第一个不重复的字符的实现
- 找到字符串第一个不重复字符
- Python字典的应用详解[转载]
- 从一个字符串中返回第一个没有重复出现的字符(例如"Hello World",返回"H")
- 使用Python开发Android应用程序:第二节 第一个有实用价值的应用
- 一道笔试题(JAVA)--求第一个无重复字符(转自论坛)
- 获取字符串中的第一个不重复的字符
- 字符串第一个重复出现的字符_超级牛逼的死想
- 经典考题——无重复字符问题(查找字符串中第一个无重复字符)
- 求第一个无重复字符
- 用最少的代码找出一个字符串中第一个不重复出现(即只出现一次)的字符
- 经典考题——无重复字符问题(查找字符串中第一个无重复字符)