剑指offer 牛客网错题记录 四

来源:互联网 发布:手机上传淘宝主图视频 编辑:程序博客网 时间:2024/06/14 01:10

题目:在一个字符串(1<=字符串长度<=10000)中找到第一个只出现一次的字符的位置。异常情况返回 -1;

 这道题借助哈希表,用空间换取运行时间,事件效率可以达到o(n) ;就是首先遍历字符串,以字符的ascii码为下标,对应的值为该字符出现的次数。再次遍历字符串,以字符为下标判断哈希表对应的值,如果为1则返回该索引项。

   代码:

<span style="color:#333333;">class Solution {public:    int g_max = 10000;    int charNum = 256;    int FirstNotRepeatingChar(string str) {        int index = -1 ;        int length = 0 ;        for(int i =0; str[i] != '\0' ; ++i){            length ++ ;        }        if(length > g_max || length < 1)  return -1 ;        int charHashTable[charNum];        for(int i =0 ;i <charNum ; ++i){            charHashTable[i] = 0;        }        for(int i = 0 ; i < length; ++i){            char temp = str[i] ;           // if( temp > 'Z' || temp < 'A') {continue;}            charHashTable[temp] ++ ;        }       for(int i = 0 ; i < length; i++){            char temp = str[i] ;            if(charHashTable[temp] == 1){                </span><span style="color:#cc0000;">index =  i;    //这里原来是 return i,这样在vs里可以编译通过,但是再牛客会说你函数没有返回值,所以定义一个变量</span><span style="color:#333333;">               </span><span style="color:#ff0000;"> break;          //index 初始化为 -1 ,这里如果不加break;返回值为最后一个出现次数为1的字符,因为找到第一个没有却没有</span><span style="color:#333333;">            }                   // t跳出!   所以测试案例通不过,对于循环一定要谨慎,。        }        return index ;    }};</span>

 

0 0
原创粉丝点击