剑指Offer 50. 第一个只出现一次的字符

方法一 indeOf方法

 1 /**
 2  * @param {string} s
 3  * @return {character}
 4  */
 5 var firstUniqChar = function(s) {
 6    for(let i=0;i<s.length;i++){
 7        f=s.indexOf(s[i]); //f记录当前字符第一次出现的位置
 8        k=s.indexOf(s[i],f+1); //从f的下一个位置开始找,若找不到则返回-1
 9        if(k === -1) return s[i];
10    }
11 
12    return ' ';
13 
14 };

方法二 哈希表

基本思想为遍历一遍s生成下标与出现次数的哈希表,再遍历一次s并在哈希表中找到其对应的value得到结果。

第二次遍历也可以通过遍历哈希表来实现,因为哈希表是去重的,既hash.length <= s.length,可以减少第二次遍历的次数。前提是哈希表中存储的数据有序。

另,因为题目要求寻找只出现一次的字符,字符为英文字母,因此可以建一个长度为26的数组,配合ASCII码将数组作为哈希表来进行操作。

 1 /**
 2  * @param {string} s
 3  * @return {character}
 4  */
 5 var firstUniqChar = function(s) {
 6     const hash = _.countBy(s);  //生成一个[s的字符, 出现次数]的对象
 7     for(const [i, ch] of Array.from(s).entries()) { // 将字符串s转化为一个浅拷贝的数组对象,并用entries()方法生成其[下标, 值]的迭代对象
 8         if(hash[ch] === 1) {
 9             return ch;
10         }
11     }
12     return ' ';
13 };

 1 /**
 2  * @param {string} s
 3  * @return {character}
 4  */
 5 var firstUniqChar = function(s) {
 6     const hash = new Map();
 7     for(const c of s) {
 8         // if(!hash.has(c)) {//hash中没有c,添加c作为key,true作为value
 9         //     hash.set(c, true);
10         // }else {//hash中有c,更新c作为key, false作为value
11         //     hash.set(c, !hash.get(c));
12         // }
13         hash.set(c, !hash.has(c));
14     }
15     for(const c of s) {
16         if(hash.get(c)) {
17             return c;
18         }
19     }
20     return ' ';
21 };

 

posted @ 2021-09-09 17:15  雪之下。  阅读(38)  评论(0)    收藏  举报