题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1.
思路:可以利用哈希表进行求解。本人使用的是进行遍历的方式进行求解
C++实现:
class Solution {
public:
int FirstNotRepeatingChar(string str) {
int t = str.length();
bool a = false;
for(int i = 0; i < t - 1; i ++)
{
if(str[i] != '0')
{
for(int j = i + 1; j < t; j ++)
{
if(str[i] == str[j])
{
str[j] = '0';
a = true;
}
}
if(a)
{
str[i] = '0';
a = false;
}
else
return i;
}
}
return -1;
}
};
python实现:
思路:利用列表可以统计字符出现次数的函数count函数来进行求解。
# -*- coding:utf-8 -*-
class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
t = len(s)
b = s
for i in range(0, t):
a = b.count(b[i])
if a == 1:
return i
return -1