题解 | #第一个只出现一次的字符#
第一个只出现一次的字符
https://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c
#include <unordered_map> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param str string字符串 * @return int整型 */ int FirstNotRepeatingChar(string str) { // write code here // 用hash map或者两个array if (str == "") return -1; std::unordered_map<char, int> hash_map; // push int i = 0; while (i < str.length()) { hash_map[str[i]]++; i++; } i = 0; while (i < str.length()) { if(hash_map[str[i]] == 1) { return i; } ++i; } return -1; } };
这个比较好理解:
1 先遍历一遍数组, 将数据放入hashmap中,每次出现相同的,就做累加
2 在遍历一次数组,返回hashmap中第一次出现1的value
note_coding 文章被收录于专栏
记录自己的解题思路, 欢迎评价