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.

Source: leetcode | Difficulty: EASY
Tags: String algorithms

Data structures

Mathematics

Starter code: class Solution:
    def firstUniqChar(self, s: str) -> int:
        

Solutions:
class Solution:

	def firstUniqChar(self, s):
		if not s:
			return -1
		elif len(s) == 1:
			return 0
		result = len(s)
		for ch in range(ord('a'), ord('z') + 1):
			if s.find(chr(ch)) == -1:
				continue
			if s.find(chr(ch)) == s.rfind(chr(ch)):
				result = min(result, s.find(chr(ch)))
		return result if result < len(s) else -1


class Solution:

	def firstUniqChar(self, s):
		letters = 'abcdefghijklmnopqrstuvwxyz'
		list = [l for l in letters if s.count(l) == 1]
		for i in range(0, len(s)):
			if s[i] in list:
				return i
		return -1


class Solution:

	def firstUniqChar(self, s):
		buffer = {}
		repeated = set()
		for i in range(len(s)):
			char = s[i]
			if char in repeated:
				continue
			if char in buffer:
				del buffer[char]
				repeated.add(char)
			else:
				buffer[char] = i
		if not buffer:
			return -1
		return sorted(list(buffer.items()), key=lambda x: x[1])[0][1]


class Solution:

	def firstUniqChar(self, s):
		inp_set = 'abcdefghijklmnoprstuvwxyz'
		indxs = [s.index(l) for l in inp_set if s.count(l) == 1]
		if len(indxs) == 0:
			return -1
		else:
			return min(indxs)


class Solution:

	def firstUniqChar(self, s):
		wholeletter = 'qwertyuioplkjhgfdsazxcvbnm'
		newindex = [s.index(x) for x in wholeletter if s.count(x) == 1]
		return min(newindex) if len(newindex) > 0 else -1


class Solution:

	def firstUniqChar(self, s):
		letters = 'abcdefghijklmnopqrstuvwxyz'
		indxs = [s.index(l) for l in letters if s.count(l) == 1]
		if len(indxs) > 0:
			return min(indxs)
		else:
			return -1


class Solution:

	def firstUniqChar(self, s):
		letters = 'abcdefghijklmnopqrstuvwxyz'
		res = len(s)
		for x in letters:
			lInd = s.find(x)
			if lInd != -1 and lInd == s.rfind(x) and (res > lInd):
				res = lInd
		return -1 if len(s) == res else res


class Solution:

	def firstUniqChar(self, s):
		chars = set(s)
		return min([s.index(char) for char in chars if s.count(char) == 1] or [-1])


class Solution:

	def firstUniqChar(self, s):
		a = set(s)
		l = [s.index(i) for i in a if s.count(i) == 1]
		if len(l) == 0:
			return -1
		else:
			return min(l)


class Solution:

	def firstUniqChar(self, s):
		s_set = set()
		for (index, char) in enumerate(s):
			if char in s_set:
				continue
			s_set.add(char)
			if s.count(char) == 1:
				return index
		return -1