题目
Given a string s
, return the first non-repeating character in it and return its index. If it does not exist, return -1
.
Example 1:
Input: s = "leetcode" Output: 0
Example 2:
Input: s = "loveleetcode" Output: 2
Example 3:
Input: s = "aabb" Output: -1
Constraints:
1 <= s.length <= 105
s
consists of only lowercase English letters.
解题
有几种思路,
1.遍历2遍,时间复杂度O(n)。
public class Solution {
public int firstUniqChar(String s) {
int freq [] = new int[26];
for(int i = 0; i < s.length(); i ++)
freq [s.charAt(i) - 'a'] ++;
for(int i = 0; i < s.length(); i ++)
if(freq [s.charAt(i) - 'a'] == 1)
return i;
return -1;
}
}
2.遍历1遍,时间复杂度O(n)
def firstUniqChar(s: str) -> int:
if len(s) < 1:
return -1
dict = {}
num=0
for i in s:
if(i in dict.keys()):
dict[i]=float("inf")
else:
dict[i]=num
num=num+1
minValue = min(dict.values())
return minValue if minValue < float("inf") else -1
print(firstUniqChar('aadadaad'))
3.这个方法从算法上来说,是O(n)。评论区大神指出,这个方法之所以快,是因为index函数是调用的C函数,因此执行快。所以这个方法让我们学到了C语言真的很快,python代码可以通过调用C函数的方式来提高执行速度,算是个小技巧。
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
letters='abcdefghijklmnopqrstuvwxyz'
index=[s.index(l) for l in letters if s.count(l) == 1]
return min(index) if len(index) > 0 else -1