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

    总结:

  • 相关阅读:
    2018/12/21 HDU-2077 汉诺塔IV(递归)
    2018-12-08 acm日常 HDU
    2018/12/12 acm日常 第二周 第六题
    git 添加远程分支,并可以code review.
    zookeeper数据迁移方法
    gem install nokogiri -v '1.6.6.2' 出错
    gem install json -v '1.8.2' error
    gem install bundle 安装失败
    全能型开源远程终端:MobaXterm
    如何写好 Git Commit 信息
  • 原文地址:https://www.cnblogs.com/missidiot/p/10783676.html
Copyright © 2011-2022 走看看