用 JavaScript 字符串中的唯一字符构造数组
我们需要编写一个 JavaScript 函数,该函数获取一个字符串并从 0 开始映射其字符。
并且每次,该函数遇到唯一的(不重复的)字符时,它应该将映射计数增加 1,否则它应该为重复的字符映射相同的数字。
例如:如果字符串为 -
const str = 'heeeyyyy';
那么输出应该是 -
const output = [0, 1, 1, 1, 2, 2, 2, 2];
因此,让我们编写此函数的代码 -
示例
代码如下 -
const str = 'heeeyyyy';
const mapString = str => {
const res = [];
let curr = '', count = -1;
for(let i = 0; i < str.length; i++){
if(str[i] === curr){
res.push(count);
}else{
count++;
res.push(count);
curr = str[i];
};
};
return res;
};
console.log(mapString(str));输出
控制台中的输出将是 -
[ 0, 1, 1, 1, 2, 2, 2, 2 ]
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP