剑指offer 34. 第一个只出现一次的字符

原题

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).

Reference Answer

思路分析

直接遍历字符串,用python dict进行次数统计,最后返回目标值对应最小的index。

# -*- coding:utf-8 -*-
class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        temp_dict = {}
        temp_index = {}
        for index, value in enumerate(s):
            if value not in temp_dict:
                temp_dict[value] = 1
                temp_index[value] = index
            else:
                temp_dict[value] += 1
        print(temp_dict)
        print(temp_index)
        res = len(s)
        for key, value in temp_dict.items():
            if value == 1:
                res = min(res, temp_index[key])
        if res == len(s):
            return -1
        else:
            return res

                

这道题时间复杂度、空间复杂度到大约是少不了了,提供一个 C++ 版本:

class Solution {
public:
    int FirstNotRepeatingChar(string str) {
        int length = str.size();
        if(length == 0){
            return -1;
        }
        map<char, int> item;
        for(int i = 0; i < length; i++){
            item[str[i]]++;
        }
        for (int i =0; i < length; i++){
            if(item[str[i]] == 1){
                return i;
            }
        }
        return -1;
    }
};

补充一个简化版:

import collections
# -*- coding:utf-8 -*-
class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        temp_res = list(filter(lambda c: s.count(c) == 1, s))
        res = s.index(temp_res[0]) if temp_res else -1
        return res         

Note

需要注意的一点是关于python中对dict进行按照key排序以及按照value排序的适用方法。

  • 按照value排序:res = sorted(temp_res.items(), key = lambda temp_res:temp_res[1])
  • 按照key排序:res = sorted(temp_res.items(), key = lambda temp_res:temp_res[0])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值