zoukankan      html  css  js  c++  java
  • 《剑指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

    总结:

  • 相关阅读:
    BZOJ 2260: 商店购物
    BZOJ 4349: 最小树形图
    BZOJ 1115: [POI2009]石子游戏Kam
    BZOJ 1413: [ZJOI2009]取石子游戏
    BZOJ 2275: [Coci2010]HRPA
    BZOJ 4730: Alice和Bob又在玩游戏
    BZOJ 1455: 罗马游戏
    BZOJ 3509: [CodeChef] COUNTARI
    BZOJ 1513: [POI2006]Tet-Tetris 3D
    #大数加减乘除#校赛D题solve
  • 原文地址:https://www.cnblogs.com/missidiot/p/10783676.html
Copyright © 2011-2022 走看看