关键
或许使用
for..of
循环遍历字符串,然后单独根据字符串是否存在于对象来统计次数比较高效,这个过程是否会自动创建一个数组?不得而知。
-
不要
不要用新数组保存遍历到的值,然后来回检查 includes ,效率低。
不必要使用字符串长度来遍历,即使测试用例中的字符不包含Unicode字符
-
字符串转为数组用于遍历
-
reduce 函数,返回一个包含字符数和检查是否存在字符的对象
-
输出结果
代码
const foo = (str) => {
const { count } = [...str].reduce(
(init, cur) => {
if (init.obj[cur] === undefined) {
init.count++;
init.obj[cur] = 1;
}
return init;
},
{ count: 0, obj: {} },
);
console.log(count);
};
foo(readline());