387. First Unique Character in a String

problem

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.
  • 在字符串中寻找第一个不重复的字母,返回位置(没有则返回-1)

solution

  1. 求一个重复字母的集合。
  2. 寻找第一个不在集合的元素
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        double = []
        
        for x in set(s):
            if s.count(x)>1:
                double.append(x)
                
        for x,y in enumerate(s):
            if y not in double:
                return x 
        return -1

discuss solution

  • 建一个包含26个字母数值的list;第一遍循环,每发现一次某字母,对其做一个标示;第二次循环,发现字母标示为(出现1次)
  • 根据字母index(first one == last one)(java特性? s.indexOf(a[i])==s.lastIndexOf(a[i]))
str.rfind(sub[, start[, end]])
Return the highest index in the string where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

str.rindex(sub[, start[, end]])
Like rfind() but raises ValueError when the substring sub is not found.
if s.find(x)==s.rfind(x):
    return s.find(x)
posted @ 2016-10-15 15:43  Salmd  阅读(108)  评论(0)    收藏  举报