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

本题来自《剑指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]!=''){                          //if not '',loop
            hashTable[str[i]]++;                      //statistic on different character
            i++;                                      //index increment
        }
        unsigned int j = 0;
        while(str[j]!=''){                          //if not '',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