第一个只出现一次的字符

题目描述

  在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置
  思路:哈希表存储出现的次数。两次遍历字符串,时间复杂度为O(n),空间复杂度为O(1)
 1 class Solution {
 2 public:
 3     int FirstNotRepeatingChar(string str) {
 4         short arr[128];
 5         memset(arr, 0, sizeof(arr));
 6         for(size_t idx=0; idx<str.size(); ++idx)
 7         {
 8             ++arr[str[idx]-'\0'];
 9         }
10         for(size_t idx=0; idx<str.size(); ++idx)
11         {
12             if(arr[str[idx]-'\0']==1)return idx;
13         }
14         return -1;
15     }
16 };

 

posted @ 2017-12-29 10:43  jeysin  阅读(93)  评论(0编辑  收藏  举报