前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T39-字符串中的第一个唯一字符

【leetcode刷题】T39-字符串中的第一个唯一字符

作者头像
木又AI帮
修改2019-07-18 10:01:16
3800
修改2019-07-18 10:01:16
举报
文章被收录于专栏:木又AI帮木又AI帮

【英文题目】(学习英语的同时,更能理解题意哟~)

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Examples:

代码语言:javascript
复制
s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.

【中文题目】

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

案例:

代码语言:javascript
复制
s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

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

【思路】

对元素进行计数,只保留数量为1的元素,查找其下标最小值即可。

由于字符串只包含小写字母,也可以直接遍历小写字母得到结果,只要计数为0或者超过1个,就continue。

【代码】

python版本

代码语言:javascript
复制
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        d = {}
        for si in s:
            d[si] = d.get(si, ) + 
        # 得到所有唯一字符
        ls = []
        for k,v in d.items():
            if v == :
                ls.append(k)
        # 找到最小下标
        if len(ls) == :
            return -1
        res =  s.index(ls[])
        for lsi in ls:
            res = min(res, s.index(lsi))
        return res

C++版本

代码语言:javascript
复制
class Solution {
public:
    int firstUniqChar(string s) {
        int res = INT_MAX;
        int place, place2;
        for(int i=; i<; i++){
            place = s.find((char)('a'+i), );
            if(place >= ){
                place2 = s.find((char)('a'+i), place+);
                if(place2 >= )
                    continue;
                else
                    res = min(res, place);
            }
        }
        if(res != INT_MAX)
            return res;
        return -1;
    }
};
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-04-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档