LeetCode--387--字符串中的第一个唯一字符


问题描述:

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

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

方法:

 1 class Solution(object):
 2     def firstUniqChar(self, s):
 3         """
 4         :type s: str
 5         :rtype: int
 6         """
 7         x = "abcdefghijklmnopqrstuvwxyz"
 8         res = []  #res=[s.index[i] for i in x if s.count(i) == 1]
 9         for i in x:
10             if i in s and s.count(i) == 1:
11                 res.append(s.index(i))
12         if len(res):
13             return min(res)
14         return -1

官方:

 1 class Solution(object):
 2     def firstUniqChar(self, s):
 3         """
 4         :type s: str
 5         :rtype: int
 6         """
 7         
 8         if s == '':
 9             return -1
10         
11         l = len(s)
12         tmp = l
13         for i in 'abcdefghijklmnopqrstuvwxyz':
14             start = s.find(i)
15             end = s.rfind(i)
16             if start != -1 and start == end:
17                 tmp = min(tmp, start)
18         if tmp < l:
19             return tmp
20         else:
21             return -1

2018-09-2816:27:05

优质内容筛选与推荐>>
1、baiduMap试手《办理进京证和市区警察查询进京证的地址浏览》
2、IIS搜索引擎优化工具包
3、【轉】研制汉字计算机的意义和可能性
4、配置了yum本地源
5、php or || 和 and &&


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn