面试题35 第一个只出现一次的字符位置

题目描述

在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符的位置。若为空串,返回-1。位置索引从0开始
 1 class Solution {
 2 public:
 3     int FirstNotRepeatingChar(string str) {
 4         if (str.length() == 0)
 5             return -1;
 6         unsigned int hashtable[256] = {0};
 7         for (int i = 0; str[i] != '\0'; i++){
 8             hashtable[str[i]]++;
 9         }
10         char ch;
11         for (int i = 0; i < str.length(); i++){
12             if (hashtable[str[i]] == 1){
13                 ch = str[i];
14                 break;
15             }
16         }
17         for (int i = 0; str[i] != '\0'; i++){
18             if (ch == str[i])
19                 return i;
20         }
21         return -1;
22     }
23 };

 

posted @ 2016-04-06 11:30  早杰  阅读(127)  评论(0编辑  收藏  举报