马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
基础算法题训练代码,看看能做出几道题
代码实现
- const array = "cncnansdnajsadnjasndjnasjdnjj";
- // 找出出现次数最多的字符
- let obj = {};
- for (let index = 0; index < array.length; index++) {
- const element = array[index];
- if (element in obj) {
- obj[element] += 1;
- } else {
- obj[element] = 1;
- }
- }
- console.log(obj);
复制代码
- // 搜索一个字符在字符串中出现的次数
- function searchStr(str, target) {
- let count = 0;
- let index = 0;
- console.log(str[count]);
- while (index < str.length) {
- if (str[index] === target) {
- count++;
- }
- index++;
- }
- return count;
- }
- const ret = searchStr(array, "a");
- console.log(ret);
复制代码
[code]// 搜索一个字符在字符串中出现的次数
// const array = "cncnansdnajsadnjasndjnasjdnjj";
function findDataTimes(str, target) {
let index = 0;
let count = 0;
while (index < str.length) {
if (str.indexOf(target, index) > -1) {
index = str.indexOf(target, index) + 1;
console.log(" |