387. First Unique Character in a String
2016-09-02 08:31
501 查看
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.
思路
首先统计每个字符的出现次数,然后遍历一次原字符串,找出第一个出现一次的字符即可。
用c语言的写法类似于389题,直接自己定义bitmap就好了
这里就用C++ 的map来写一遍
代码(C++)
代码(python)
学习总结
这个python的代码我是学习了这里,我自己也写了一套python的代码,没这个简洁,就不贴了。
关于collections.Counter()前面这里已经讲过了
enumerate()学习:
enumerate函数用于遍历序列中的元素以及它们的下标,在python中enumerate的用法多用于在for循环中得到计数。
例1:
输出:
例2:
输出:
examples:
s = "leetcode" return 0. s = "loveleetcode", return 2.
Note: You may assume the string contain only lowercase letters.
思路
首先统计每个字符的出现次数,然后遍历一次原字符串,找出第一个出现一次的字符即可。
用c语言的写法类似于389题,直接自己定义bitmap就好了
这里就用C++ 的map来写一遍
代码(C++)
class Solution { public: int firstUniqChar(string s) { if(s.empty()) return -1; int len = s.size(); map<char, int> map_str; for (int i = 0; i < len; i++) { map_str[s[i]]++; } for (int i = 0; i < len; i++) { if (1 == map_str[s[i]]) return i; } return -1; } };
代码(python)
class Solution(object): def firstUniqChar(self, s): """ :type s: str :rtype: int """ dic = collections.Counter(s) res = -1 for index, ch in enumerate(s): if dic[ch] == 1: res = index break return res
学习总结
这个python的代码我是学习了这里,我自己也写了一套python的代码,没这个简洁,就不贴了。
关于collections.Counter()前面这里已经讲过了
enumerate()学习:
enumerate函数用于遍历序列中的元素以及它们的下标,在python中enumerate的用法多用于在for循环中得到计数。
例1:
import string s = string.ascii_lowercase e = enumerate(s) print s print list(e)
输出:
abcdefghij [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j')]
例2:
i = 0 seq = ['one', 'two', 'three'] for element in seq: print i, seq[i] i += 1 print '===========' i = 0 seq = ['one', 'two', 'three'] for i, element in enumerate(seq): print i, seq[i]
输出:
0 one 1 two 2 three =========== 0 one 1 two 2 three
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解