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

时间:2023-03-09 17:14:04
[剑指Offer] 34.第一个只出现一次的数

题目描述

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

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

 class Solution
{
public:
int GetLastIndex(char c,string str)
{
for(int i = str.length() - ; i >= ; i --)
{
if(str[i] == c)
{
return i;
}
}
return -;
}
int FirstNotRepeatingChar(string str)
{
if(str == "") return -;
int id = -;
bool judge[str.length()];
for(int i = ; i < str.length(); i ++)
judge[i] = false;
for(int i = ; i < str.length(); i ++)
{
id = GetLastIndex(str[i],str);
if(id == i && !judge[i])
return i;
judge[i] = judge[id] = true;
}
return -;
}
};