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.
My solutions:
import sys
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
unique_map = dict()
sort_list = list()
size = len(s)
if size < 1:
return -1
for i in range(size):
if s[i] in unique_map:
unique_map[s[i]] = sys.maxsize
continue
unique_map[s[i]] = i
for k, v in unique_map.items():
sort_list.append(v)
sort_list.sort()
if sort_list[0] == sys.maxsize:
return -1
return sort_list[0]
Good solutions:
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
str_list = list()
size = len(s)
for string in s:
if string not in str_list:
str_list.append(string)
for string in str_list:
if s.count(string) == 1:
return s.index(string)
return -1
'DataStructure > Strings' 카테고리의 다른 글
String to Integer (atoi) (0) | 2018.10.23 |
---|---|
Valid Palindrome (0) | 2018.10.23 |
Valid Anagram (0) | 2018.10.23 |
Reverse Integer (0) | 2018.10.22 |
Reverse String (0) | 2018.10.22 |