《剑指offer》第一个只出现一次的字符

本文介绍了一种使用哈希表和数组统计字符频率的方法,以找出字符串中首次出现的唯一字符及其位置。通过C++和Python代码实现,适用于字符串长度不超过10000的情况。

本题来自《剑指offer》 第一个只出现一次的字符

题目:

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

思路:

   采用华哈希表的方式,python直接有count方法,可以直接统计得出。

  c++采用数组的方式模拟哈希表,key为字符,value为次数。

C++ Code:

class Solution {
public:
    int FirstNotRepeatingChar(string str) {
        
        const int tableSize = 256;                    //cache size
        unsigned int hashTable[tableSize];            //hash cache
        for (unsigned int i=0;i<tableSize;i++){       //loop cache
            hashTable[i] = 0;                         //set the inital value to 0
        }
        unsigned int i = 0;               
        while(str[i]!='\0'){                          //if not '\0',loop
            hashTable[str[i]]++;                      //statistic on different character
            i++;                                      //index increment
        }
        unsigned int j = 0;
        while(str[j]!='\0'){                          //if not '\0',loop
            if (hashTable[str[j]]==1){                //only if the index of character equal 1,which we want
                return j;                             //return the index,that’s result
            }
            j++;                                      //index increment
        }
        return -1;                                    //return negative 1 when none of previous program are executed
    }
};

Python Code:

# -*- coding:utf-8 -*-
class Solution:
    def FirstNotRepeatingChar(self, s):
        if not s or len(s)>10000:             #boundary condition judgement
            return -1
        else:
            for word in s:                    #loop traversal as for word in s
                if s.count(word) == 1:        #the count method is a libary in python,only the count is 1,is result
                    return s.index(word)      #return the index of this word

总结:

转载于:https://www.cnblogs.com/missidiot/p/10783676.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值