【LeetCode 简单题】85-字符串中第一个唯一字符

声明:

今天是第85道题。给定n,从 1 到 n 选择一个数字。 你需要猜我选择了哪个数字。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除

(手动比心ღ( ´・ᴗ・` ))

正文

题目:给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

注意事项:您可以假定该字符串只包含小写字母。

解法1。用一个字典存放输入字符串出现的字符极其出现频数的对应关系,然后再去遍历字符串s,一旦找到频数为1的字符即返回对应index,代码如下。

执行用时: 128 ms, 在First Unique Character in a String的Python提交中击败了71.65% 的用户

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        # 基线条件,判断输入为空时的情况
        if not s:
            return -1

        s_dict = {}
        for i in s:
            if i not in s_dict:
                s_dict[i] = 1
            else:
                s_dict[i] += 1
        for i in range(len(s)):
            if s_dict[s[i]] == 1:
                return i
            else:
                continue
        return -1

解法2。利用内置字符串属性s.count(i)和s.index(i)遍历字符串然后返回下标最小的那个下标,代码如下。

执行用时: 64 ms, 在First Unique Character in a String的Python提交中击败了86.02% 的用户 

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        lis = [s.index(i) for i in s if s.count(i) == 1]
        return min(lis) if lis else -1

 解法3。也是利用字符串属性s.find(i)和s.rfind(i)遍历字符串,如果只出现1次的话那么这2者的值应该是一样的,没找到则返回-1,代码如下。

执行用时: 300 ms, 在First Unique Character in a String的Python提交中击败了25.20% 的用户

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return -1
        s_str = s
        l = len(s)
        p = l
        for i in s_str:
            start = s.find(i)
            end = s.rfind(i)
            if start != -1 and start == end:    # 找得到该字符且只出现了1次,其实这个地方完全可以去掉start != -1这个判断条件
                p = min(p,start)
        if p == l:
            return -1    # 说明p没有被更新,没找到只出现1次的字符
        return p

结尾

解法1:原创

解法2&解法3:LeetCode

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/83961554