[剑指Offer] 34.第一个只出现一次的数

题目描述

在一个字符串(1<=字符串长度<=10000,全部由大写字母组成)中找到第一个只出现一次的字符,并返回它的位置

【思路】当一个字符第一次出现的位置和它最后一次出现的位置相同,那么它就是只出现一次的数

 1 class Solution
 2 {
 3 public:
 4     int GetLastIndex(char c,string str)
 5     {
 6         for(int i = str.length() - 1; i >= 0; i --)
 7         {
 8             if(str[i] == c)
 9             {
10                 return i;
11             }
12         }
13         return -1;
14     }
15     int FirstNotRepeatingChar(string str)
16     {
17         if(str == "")    return -1;
18         int id = -1;
19         bool judge[str.length()];
20         for(int i = 0; i < str.length(); i ++)
21             judge[i] = false;
22         for(int i = 0; i < str.length(); i ++)
23         {
24             id = GetLastIndex(str[i],str);
25             if(id == i && !judge[i])
26                 return i;
27             judge[i] = judge[id] = true;
28         }
29         return -1;
30     }
31 };

 

posted @ 2017-03-07 09:37  Strawberry丶  阅读(171)  评论(0编辑  收藏  举报