hash表
//题目描述
//在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符的位置。若为空串,返回-1。位置索引从0开始
#include<iostream>
#include<string>
using namespace std;
class Solution {
public:
int FirstNotRepeatingChar(string str) {
int n=str.size();
if(n==0)return -1;
int hash[256]={0};
for(int i=0;i<n;i++)
hash[str[i]]++;
for(int i=0;i<n;i++)
if(hash[str[i]]==1)return i;
return -1;
}
};
int main(){
Solution test=Solution();
string s="google";
cout<<test.FirstNotRepeatingChar(s)<<endl;
return 0;
}
注意:在java中int类型不赋值,默认值为0,c/c++中全局变量的话,默认为0,但对于局部变量不赋初值,其中的值就不一定为多少了,编译器只负责为该变量分配一个地址,因此在c/c++中主要要进行初始化。