题目: 在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数) 方法:哈希法 遍历一遍字符串,统计每个字符出现的次数。然后再遍历一遍字符串,找出答案。 一:用map实现
#include<unordered_map> class Solution { public: int FirstNotRepeatingChar(string str) { unordered_map<char,int>help; for(const char val:str){//一次遍历计算每个字符出现的次数 ++help[val]; } for(int i=0;i<str.length();++i){//二次遍历找到第一个次数为1 的字符 if(help[str[i]]==1){ return i; } } return -1; } };二:用数组代替map
class Solution { public: int FirstNotRepeatingChar(string str) { int help[128]={0}; for(const char val:str){//一次遍历计算每个字符出现的次数 ++help[val]; } for(int i=0;i<str.length();++i){//二次遍历找到第一个次数为1 的字符 if(help[str[i]]==1){ return i; } } return -1; } };时间复杂度:O(2n), 需要遍历两次字符串 空间复杂度:O(n)