第 114 题:找出字符串中连续出现最多的字符和个数
yygmind opened this issue · 121 comments
'abcaakjbb' => {'a':2,'b':2}
'abbkejsbcccwqaa' => {'c':3}
注意:题目说的是连续出现,注意连续二字
const arr = str.match(/(\w)\1*/g);
const maxLen = Math.max(...arr.map(s => s.length));
const result = arr.reduce((pre, curr) => {
if (curr.length === maxLen) {
pre[curr[0]] = curr.length;
}
return pre;
}, {});
console.log(result);
暴力版
function getStrMaxLengthObj (str) {
if (!str) { return {} }
let strObj = {}
let res = {}
let max = 0
let currentLetter = ''
for (let i = 0; i < str.length; i ++) {
let item = str[i]
if (currentLetter === item) {
strObj[item] += 1
} else {
currentLetter = item
strObj[item] = 1
}
if (strObj[item] > max) {
max = strObj[item]
res = {}
res[item] = max
} else if (strObj[item] === max) {
res[item] = max
}
}
return res
}
console.log(getStrMaxLengthObj('abbkejsbcccwqaa')) //- {c:3}
一次遍历
function findLongest(str) {
if (!str) return {}
let count = 0
let maxCount = 0
let cur = str[0]
let res = {}
for (let i = 0; i < str.length; i++) {
const s = str[i]
if (s === cur) {
count++
if (count > maxCount) {
res = { [s]: count }
maxCount = count
}
if (count === maxCount) {
res[s] = count
}
} else {
count = 1
cur = s
}
}
return res
}
时间复杂度O(n), 空间复杂度O(1)
function getMax(str) {
let c = "";
let res = Array.from(str).reduce((acc, cur) => {
if (c == cur) {
acc[cur] = acc[cur] ? acc[cur] + 1 : 2;
} else {
acc[cur] = 1;
}
c = cur;
return acc;
}, {});
let max = Math.max.apply(null, Object.values(res));
let ret = {};
for (let k in res) {
if (res[k] == max) {
ret[k] = max;
}
}
return ret;
}
console.log(getMax("abbkejsbcccwqaa")); //{c: 3}
console.log(getMax("abcaakjbb")); //{a: 2, b: 2}
const func = (str) => {
let temp = '-1'
let count = 0
let maxCount = 0
// 传入的字段串增加一位,防止以连续字母结尾的统计出错
str += '-1'
const res = {}
while(str.length > 0) {
// 相同字符串,统计+1
if (temp === str[0]) {
count ++
res[temp] = count
} else {
// 遇到不同,比较当前连续的字符是否是最长的
if (res[temp] >= maxCount) {
maxCount = res[temp]
} else {
delete res[temp]
}
count = 1
temp = str[0]
}
str = str.substring(1)
}
return res
}
// const str = 'abbkejsbcccwqaa'
const str = 'abcaakjbb'
const res = func(str)
console.log('res', res)
function findChar(char) {
let obj = {};
let reg = /(\w)\1/g;
char.match(reg).map(str = >Object.keys(obj).indexOf(str) > -1 ? obj[str] = obj[str] + str.length: obj[str] = str.length);
return obj
}
findChar('abbkejsbbcccwqaa');
function find(str){
let Obj={};
str.split('').reduce((o,p,index)=>{
o===p?(Obj[o]?Obj[o]=Obj[o]++:Obj[o]=2):null
return p
});
Object.keys(Obj).forEach(k=>{
if(Obj[k]!==Math.max(...Object.values(Obj))){
delete Obj[k]
}
});
return Obj;
}
'aaasdofjaopfjopaiiisjssfopiasdfffff'.match(/(.)\1+/g)
得到的结果是
["aaa", "iii", "ss", "fffff"]
从这个数组里面找长度最长的元素并转化成需要的结果应该简单了吧
const str114 = 'abcaakjbb';
let r = str114.substr(1)
const obj114 = str114.split('').reduce((pre, current) => {
if (r === current) {
pre[current] += 1
} else {
pre[current] = 1
}
r = current
return pre;
}, {});
const max114 = Math.max(...Object.values(obj114));
for (const i in obj114) {
if (obj114[i] !== max114) delete obj114[i]
}
console.log(obj114);
习惯了用正则处理一些字符串的问题,感觉还可以优化,期待大佬版本
添加最大长度为1的情况
function searchLongChar(str, max = 0, obj = {}) {
// 提取重复串组合
let arr = str.match(/(\w)\1+/g);
if(arr==null) return;
arr.map(v => {
let l = v.length;
if (max <= l) {
// 重置数组
if (max < l) obj = {};
// 赋值
obj[v.substr(-1)] = max = l;
}
})
return obj;
}
Object.fromEntries 是 ES10 语法,使用高版本的浏览器或者 NodeJs 版本运行
function func(str) {
let obj = str.split("").reduce((pre, cur) => {
pre[cur] ? pre[cur]++ : pre[cur] = 1
return pre
}, {})
let maxNum = Math.max(...Object.values(obj)) // 获取最多的次数
let entries = Object.entries(obj).filter(([_, value]) => value === maxNum) // 过滤出出现最多次数的键值对
return Object.fromEntries(entries) // 将键值对转换为对象(ES10 语法)
}
console.log(func('abcaakjbb'))
console.log(func('abbkejsbcccwqaa'))
function operate(str){
let obj = {},max = 1,temp=[]; // temp保存上一个值与连续次数 如[a,1];
for(let i = 0;i<str.length;i++){
if(!temp.length){
temp = [str[i],1],max = 1,obj[str[i]] = 1;
}else if(temp[0] == str[i]){
temp[1] += 1;
if(temp[1] > max){
obj = {},max = temp[1],obj[temp[0]] = temp[1];
}else if (temp[1] == max){
obj[temp[0]] = temp[1]
}
}else{
if(max == 1){
temp = [str[i],1],obj[str[i]] = 1;
}else{
temp = [str[i],1]
}
}
}
return obj
}
console.log(operate('abcaakjbb')) // {a: 2, b: 2}
console.log(operate('abcakjb')) // {a: 1, b: 1, c: 1, k: 1, j: 1}
console.log(operate('abbkejsbcccwqaa')) //{c: 3}
function getMax (str) {
var arr = [...new Set(str.split(''))]
var _arr = []
var _len = []
arr.map((o, i) => {
var reg = new RegExp(`(${o}+)`, 'g')
var match = [...str.matchAll(reg)]
var length = match.map((m, mi) => m[0].length).sort((a, b) => b - a)[0]
_arr.push([o, length])
_len.push(length)
})
var max = _len.sort((a, b) => b - a)[0]
var maxArr = _arr.filter((o, i) => o[1] === max)
return Object.fromEntries(maxArr)
}
全面通用~~~
getMax('abc') // {a:1,b:1,c:1}
getMax('abcaakjbb') // {a: 2, b: 2}
getMax('abbkejsbcccwqaa') //{c: 3}
getMax('assssssssssssssssbaasdasdasdasgfsgsgsadgc') ////{s: 16}
Object.fromEntries 是 ES10 语法,使用高版本的浏览器或者 NodeJs 版本运行
function func(str) { let obj = str.split("").reduce((pre, cur) => { pre[cur] ? pre[cur]++ : pre[cur] = 1 return pre }, {}) let maxNum = Math.max(...Object.values(obj)) // 获取最多的次数 let entries = Object.entries(obj).filter(([_, value]) => value === maxNum) // 过滤出出现最多次数的键值对 return Object.fromEntries(entries) // 将键值对转换为对象(ES10 语法) } console.log(func('abcaakjbb')) console.log(func('abbkejsbcccwqaa'))
是连续出现最多,不是出现最多
上面的麻烦学学markdown语法再发好吗?看着难受
在```后面加上javascript
function getMaxCharacters(str) {
const map = {}
var arr = str.match(/(\w)\1+/g)
var max = arr[0].length
arr.map(v => max = Math.max(max, v.length))
const maxArr = arr.filter(v => v.length === max)
maxArr.forEach(v => {
map[v[0]] = v.length
})
return map
}
getMaxCharacters('abcaakjbb') // { a: 2, b: 2 }
const str = 'abbkejsbcccwqaa'
function fn(str) {
let i = 0
let result = {}
let prev = ''
let max = 0
while(i < str.length) {
const cur = str[i]
if (prev === cur) {
if (result[prev]) {
result[prev]++
} else {
result[prev] = 2
}
max = Math.max(result[prev], max)
}
prev = str[i]
i++
}
return Object.keys(result).reduce((prev, key) => {
const val = result[key]
if (val === max) {
prev[key] = val
}
return prev
}, {})
}
console.log(fn(str))
强行使用map保存了每个连续字符串的个数,然后在使用遍历找到出现次数最多的一个或者多个
function searchMaxStr(str) {
let map = new Map();
let result = {}//保存最后的结果
let middle = str[0];
let count = 0;
for (let i = 0, length = str.length; i < length; i++) {
let temp = str[i];
if (temp == middle) {
count++;
if (map.has(temp)) {
if (count > map.get(temp)) {
map.set(temp, count)
}
} else {
map.set(temp, count)
}
} else {
count = 0;
i = i - 1;
middle = temp;
}
}
let bianli = 0;
for (let key of map.keys()) {
value = map.get(key)
if (bianli < value) {
bianli = value;
if (Object.keys(result) != 0) {
result = {}
} else {
result[key] = value;
}
}
if (bianli == value) {
result[key] = value
}
}
return result;
}
function getCharts(str) {
debugger;
let obj = {};
let max = {};
let len = str.length;
if (len > 1) {
for (let i = 1; i < len; i++) {
if (str[i - 1] == str[i]) {
//obj[str[i]] += 1;
if (!obj[str[i]]) {
obj[str[i]] = 2;
} else {
obj[str[i]] += 1;
}
}
}
}
let maxNum = Math.max.apply(null, Object.values(obj));
for (let key in obj) {
if (obj[key] == maxNum) {
max[key] = maxNum;
}
}
return max;
}
function getMuitipleChar(str) {
let result = {}
var reg = /(\w)\1{1,}/g
let multi = str.match(reg)
if (multi && multi.length > 0) {
result = multi.reduce((res, current) => {
let currLen = current.length
let keys = Object.keys(res)
let len = res[keys[0]] || 0
if (currLen < len) return res
res[current[0]] = currLen
if (currLen > len) {
res = {
[current[0]]: currLen
}
}
return res
}, {})
}
return result
}
// 'abcaakjbb' => {'a':2,'b':2}
// 'abbkejsbcccwqaa' => {'c':3}
// 注意:题目说的是连续出现,注意连续二字
function getMaxTimes(str) {
var maxMap = {};
let currentTimes = 0;
let maxTimes = 0;
let char;
let nextChar;
for (let i = 0, len = str.length; i < len; ) {
char = str[i];
// 检查下一个...
let j = 0;
do {
j++;
nextChar = str[i + j];
currentTimes++;
} while (nextChar === char);
maxMap[char] = currentTimes;
// 顺便记录下最大出现次数
if (currentTimes > maxTimes) maxTimes = currentTimes;
currentTimes = 0;
i += j;
}
// 去掉无用的记录
Object.keys(maxMap).forEach(k => {
if (maxMap[k] !== maxTimes) delete maxMap[k];
});
return maxMap;
}
console.log(getMaxTimes('abcaakjbb'));
console.log(getMaxTimes('abbkejsbcccwqaa'));
空间复杂度: O(1);时间复杂度: O(N)
function getMaxContinuousStrLen(str) {
if (typeof str !== 'string' || !str.length) {
return ['', 0]
}
const length = str.length
let last = str[0],
times = 1,
maxTimes = 0,
maxChar = ''
for (let i = 1; i < length; ++i) {
if (str[i] === last) {
++times
} else {
if (times > maxTimes) {
maxChar = last
maxTimes = times
}
times = 1
last = str[i]
}
}
if (times > maxTimes) {
maxChar = last
maxTimes = times
}
return [maxChar, maxTimes]
}
// 测试代码
console.log(getMaxContinuousStrLen('b')) //[ 'b', 1 ]
console.log(getMaxContinuousStrLen('abb')) //[ 'b', 2 ]
console.log(getMaxContinuousStrLen('abbkejsbcccwqaa')) // [ 'c', 3 ]
console.log(getMaxContinuousStrLen('abcaakjbb')) // [ 'a', 2 ]
function findTargetStr(str) {
return (str.match(/(.)\1*/g) || []).reduce((res, cur) =>
(
cur.length > res.max ?
(res.r = { [cur[0]]: cur.length }, res.max = cur.length) :
(cur.length === res.max && (res.r[cur[0]] = res.max)
), res), { r: {}, max: 0 }).r
}
const findMaxConstantString = str => {
const result = []
str.replace(/(\S\w)(\1)+/g, matched => {
result.push({[matched[0]]:matched.length})
})
return Object.assign(...result.filter( oRes => Object.values(oRes)[0] === Math.max(...result.map(counter =>Object.values(counter)[0]))))
}
// 好多大佬。。。献上我的渣渣版本 好多地方还可以优化
function getMax(){
let str = 'bacdd33333';
let arr = [];
let arr1 = [];
let count = 1;
let max = null;
let obj = {};
for(let i=0;i<str.length;i++){
if(str[i] == str[i+1]){
count+=1;
}else{
count = 1;
}
arr1.push(count);
arr.push({key:str[i],count:count});
max = Math.max(...arr1);
}
for(let item of arr){
if(item.count == max){
obj[item.key] = item.count
}
}
return obj;
}
getMax()
菜鸟版本
const a = 'abcaakjbb'; const b = 'abbkejsbcccwqaa'
function findLetter (str = '') {
const res = str.match(/(.)\1+/g).reduce((acc, next) => {
const maxLen = Math.max(Object.values(acc))
const nextObj = { [next.charAt(0)]: next.length }
const newAcc = maxLen > next.length ? acc : (maxLen === next.length ? Object.assign(acc, nextObj) : nextObj)
return newAcc
}, {})
return res
}
console.log(findLetter(b)) // { c: 3 }
console.log(findLetter(a)) // { a: 2, b: 2 }
function searchMaxStr(str) {
const result = {}
const continuous = str.match(/(\w)\1+/g)
const max = continuous.reduce((max, curStr) => curStr.length > max ? curStr.length : max, 0)
continuous.forEach(item => {
if (item.length === max) {
result[item] = max
}
})
return result
}
searchMaxStr('abcaakjbb')
searchMaxStr('abbkejsbcccwqaa')
var s = 'awo[eigoawjeogpawkegak11111111111wef,.xcmvjawoegjawjegoaiwjsdm,.vmkadjsfawgefo eighaerg4a5g4'
function func(s){
var Obj = s.split('').reduce((acct, cur) => {
let item = acct[cur];
item = item ? item + 1 : 1
return { ...acct, [cur]: item }
}, {})
var max = Math.max(...Object.values(Obj))
return Object.keys(Obj).reduce((acct, cur) => Obj[cur] === max ? { ...acct, [cur]: Obj[cur] }:acct,
{})
}
func(s)
看大佬们都使用正则表达式进行匹配,小弟就不用正则来个版本
主要思路如下:
-
想要计算出现的次数,则需要遍历,这里通过Array.prototype.reduce方法,遍历每一个字符
-
题目又说是连续出现,那么只要单个字符出现2次以上,就要储存,所以这里在遍历的时候,通过reduce的第二个参数保存一个temp对象。
-
根据temp中该字符重复出现的次数就行逻辑判断。
如果一旦发现
temp
对象中不存在[next]属性
,则表示next并不是连续字符
,所以完全覆盖temp
对象 -
结果出来以后,删除
strToObj
中的temp
属性。 -
通过
Math.max
以及Object.values
方法找出最大值max
。 -
filter
对象strToObj
,找出值等于max
的。 -
最后在使用
reduce
拼接结果返回。
const findMaxRepeatString = str => {
if (typeof str !== 'string') return {};
const strToObj = Array.prototype.reduce.call(
str,
(pre, next) => {
let track = pre.temp[next];
if (!track) {
pre.temp = {
[next]: 1,
};
return pre;
}
track = ++pre.temp[next];
if (track < 2) return pre;
const v = track - (pre[next] || 0);
pre[next] = v >= 1 ? track : pre[next];
return pre;
},
{ temp: {} }
);
delete strToObj.temp;
const max = Math.max(...Object.values(strToObj));
if (max < 2) return {};
return Object.keys(strToObj)
.filter(key => strToObj[key] === max)
.reduce((pre, key) => {
pre[key] = strToObj[key];
return pre;
}, {});
};
findMaxRepeatString ('aa11bbbppbbb'); // { b: 3 }
这么多大佬,自己就是个渣渣 😫
export function findLargeNumObj (str = '') {
if (!str) {
return {}
}
let result = {}
let arr = str.match(/(\w)\1*/g) // \1表示第一个括号内的内容
let maxLen = Math.max(...arr.map(s => s.length))
arr.forEach(item => {
if (item.length === maxLen) {
result[item.split('')[0]] = maxLen
}
})
return result
}
function filterMaxKey (str) {
let matchg = str.match(/(\w)\1+/g) || [] // 获取连续字符
let max = Math.max([...matchg].length) // 得到连续字符最大值
return matchg.reduce((per, cur, idx) => {
if (cur.length === max) {
per[cur[0]] = max
}
return per
}, {})
}
console.log(filterMaxKey('abcaakjbb'))
console.log(filterMaxKey('abbkejsbcccwqaa'))
代码:
function findMaxObj(str) {
let i = str.length - 1;
let result = {}; //存结果
let maxLength = 0; //存当前字符个数最大值
while (i > 0) {
let res = {}; //临时存储当前索引的字符及连续出现的个数
let key = str[i];
res[key] = 1;
i--;
while (str[i] && str[i] === str[i + 1]) { //连续字符个数
res[str[i + 1]]++;
i--;
}
if (res[key] > maxLength) {
maxLength = res[key];
result = {}; //出现新的最大值,置空
result[key] = result[key] ? Math.max(result[key], res[key]) : res[key];
} else if (res[key] === maxLength) {
result[key] = result[key] ? Math.max(result[key], res[key]) : res[key];
}
}
console.log(result)
return result;
};
结果:
findMaxObj('ajoimlerjojjqwepqweododdddp');
//{d: 4}
findMaxObj('ajoimlerjojjqwepqweododdddppppa');
//{p: 4, d: 4}
findMaxObj('appppjoimlerjojjqwepqweododdddppppa');
//{p: 4, d: 4}
findMaxObj('appppjjjjoimlerjojjqwepqweododdddppppa');
//{p: 4, d: 4, j: 4}
var continuestr=function(str){
var arr=str.split("");
var index=1;
var max=index;
var obj={};
for(let i=0;i<arr.length-1;i++)
{
if(arr[i]!=arr[i+1])
{
//obj[arr[i]]=index;
index=1;
}
else
{
index++;
max=max>=index?max:index;
obj[arr[i]]=index;
}
}
var result={};
if(max!=1)
{
for(var i in obj)
{
if(obj[i]==max)
{
result[i]=max;
}
}
}
else
{
for(let i=0;i<arr.length;i++)
{
result[arr[i]]=1;
}
}
return result;
};
function maxStr(str) {
const arr = str.split('');
let obj = {};
let max = 1;
let maxValue = arr[0];
for (let i = 0; i < arr.length; i++) {
let cur = arr[i];
let j = 1;
while (cur === arr[i + 1]) {
cur = arr[i + 1];
i++;
j++;
}
if (j > 1) {
max = Math.max(max, j);
maxValue = max > j ? maxValue : cur;
if (max > j) {
obj = {};
obj[maxValue] = max;
} else if (max === j) {
obj[maxValue] = max;
}
} else {
obj[cur] = 1;
}
}
const keys = Object.values(obj);
max = Math.max.apply(null, keys);
let res = {};
for (const i in obj) {
if (obj[i] === max) {
res[i] = max;
}
}
return res;
}
一次遍历
function findLongest(str) { if (!str) return {} let count = 0 let maxCount = 0 let cur = str[0] let res = {} for (let i = 0; i < str.length; i++) { const s = str[i] if (s === cur) { count++ if (count > maxCount) { res = { [s]: count } maxCount = count } if (count === maxCount) { res[s] = count } } else { count = 1 cur = s } } return res }时间复杂度O(n), 空间复杂度O(1)
没有重复的话筛选就出错了
function handle (string) {
let max = 0
let result = {}
const chars = string.match(/(.)\1*/g) || [] // [ 'a', 'b', 'c', 'aa', 'k', 'j', 'bb' ]
for (const char of chars) {
const length = char.length
if (max < length) max = length
if (!result[length]) result[length] = {}
result[length][char[0]] = length
}
return result[max] || {}
}
handle('abcaakjbb') // { a: 2, b: 2 }
function test (str) {
let flag = {}
let result = {}
let len = str.length
let pre = ''
let max = 0
for (let i = 0; i < len - 1; i ++) {
let current = str.charAt(i)
if (current === pre) {
flag[current] += 1
if (flag[current] > max) {
max = flag[current]
result = {
[current]: max
}
} else if (flag[current] === max) {
result[current] = max
}
} else {
pre = current
flag[current] = 1
if (i === 0) {
max = flag[current]
result[current] = max
}
}
}
return result
}
最基础的写法
let str = 'abcaakjbb'
function maxString(str) {
let calcCountObj = Array.from(str).reduce((prev, item, index, arr) => {
let key = index
if (!prev[item]) {
prev[item] = 1
while (arr[++key] == item) {
prev[item]++
}
} else {
let count = 1
while (arr[++key] == item) {
count++
}
if (count > prev[item]) {
prev[item] = count
}
}
return prev
}, {})
let max = Math.max(...Object.values(calcCountObj))
let Obj = {}
for (let item in calcCountObj) {
calcCountObj[item] === max && (Obj[item] = max)
}
return Obj
}
let res = maxString(str)
console.log(res)
function countMax(str) {
let count = 1;
return Array
.from({ ...str, length: str.length })
.reduce((r, c, i, arr) => {
if (c === arr[i + 1]) {
count++;
} else {
r = count > r[0] ? [count, arr[i-1]] : r[0] === count ? [...r, arr[i-1]] : r;
count = 1;
}
return r;
}, [0])
.reduce((r, k, i, arr) => {
i && (r[k] = arr[0]);
return r;
}, {});
}
const arr = str.match(/(\w)\1*/g); const maxLen = Math.max(...arr.map(s => s.length)); const result = arr.reduce((pre, curr) => { if (curr.length === maxLen) { pre[curr[0]] = curr.length; } return pre; }, {}); console.log(result);
正则表达式写错了,应该用+,而不是*
/(\w)\1+/g
function fuck(str) {
let res = {}, prev = '', max = 0
str.split('').forEach(key => {
res[key] ? (prev === key && res[key]++) : (res[key] = 1)
prev = key
})
max = Math.max(...Object.values(res))
for (const key in res) {
res[key] < max && (delete res[key])
}
console.log(res)
}
function fun1(str) {
let obj = {}
for (let i = 0; i < str.length; i++) {
let key = str[i]
if (str[i] == str[i + 1]) {
if (obj[key]) {
obj[key] += 1
} else {
obj[key] = 2
}
}
}
let result = {}
let max_value = 0
let max_key = ''
Object.keys(obj).forEach(key => {
if (obj[key] > max_value) {
max_value = obj[key]
max_key = key
}
})
result[max_key] = max_value
Object.keys(obj).forEach(key => {
if (obj[key] == max_value) {
result[key] = obj[key]
}
})
return result
}
let string = 'acmmdssscdd'
let fn = (str) => {
let strArr = str.split('') // 切割成数组
let result = {} // 初始化返回结果
let max = 1 // 初始化连续最大数
strArr.reduce((prev, next, index, arr) => {
if (next === arr[index + 1]) { // 如果相等 迭代次数++
prev ++
return prev
} else {
// 不相等 判断是否至少二次 且 大于等于连续最大数
if (prev > 1 && prev >= max){
// 如果大于最大数 则把result对象清空 连续最大数为prev
if (prev > max){
result = {}
max = prev
}
result[next] = prev // 赋值
}
prev = 1 // 清空连续迭代数
return prev
}
}, 1)
return result
}
console.log(fn(string)) // {s: 3}
const arr = str.match(/(\w)\1*/g); const maxLen = Math.max(...arr.map(s => s.length)); const result = arr.reduce((pre, curr) => { if (curr.length === maxLen) { pre[curr[0]] = curr.length; } return pre; }, {}); console.log(result);
正则表达式写错了,应该用+,而不是*
/(\w)\1+/g
你考虑到长度最长是一位的情况吗?
跟大家一样用了正则 🤔
const getMaxContiniu = (str = '') => {
const res = {};
let max = 0;
arr = str.match(/(.)\1+/g)
if (!arr) return res;
arr.map((item) => {
const l = item.length;
if (l >= max) {
const k = item[0];
max = l;
res[k] = max;
}
})
return res;
}
getMaxContiniu('aaacccbbadi') // {a: 3, c: 3}
const arr = str.match(/(\w)\1*/g); const maxLen = Math.max(...arr.map(s => s.length)); const result = arr.reduce((pre, curr) => { if (curr.length === maxLen) { pre[curr[0]] = curr.length; } return pre; }, {}); console.log(result);
正则表达式写错了,应该用+,而不是*
/(\w)\1+/g
你考虑到长度最长是一位的情况吗?
长度最长是一的话还是“连续出现”吗?
const arr = str.match(/(\w)\1*/g); const maxLen = Math.max(...arr.map(s => s.length)); const result = arr.reduce((pre, curr) => { if (curr.length === maxLen) { pre[curr[0]] = curr.length; } return pre; }, {}); console.log(result);
正则表达式写错了,应该用+,而不是*
/(\w)\1+/g
你考虑到长度最长是一位的情况吗?
长度最长是一的话还是“连续出现”吗?
省的抠字眼,思路没问题就行
//找出字符串中连续出现最多的字符和个数
/*'abcaakjbb' => {'a':2,'b':2}
'abbkejsbcccwqaa' => {'c':3}*/
findMaxCount('abbkejsbcccwqaa')
//层主比较low,用顺序比较法。。
function findMaxCount(string){
let arr = string.split('')
let objArr = [],max = 0
//第一个字符和后面的字符比较,相同+1,不同就break
for(let i=0;i<arr.length-1;i++){
let count = 0
for(let j=i+1;j<arr.length;j++){
if(arr[i] === arr[j]){
count++
}else{
break
}
}
//记住最大的数
if(max<=count){
max = count
}
//把每个字母比较出现的次数 放入新数组
objArr.push({
name: arr[i],
count: count+1
})
}
let returnArr = []
//通过max找出objArr中的字母,然后放入新数组
objArr.map((item)=>{
if(item.count === max+1){
returnArr.push(item)
}
})
console.log(returnArr)
return returnArr
}
const arr = str.match(/(\w)\1*/g); const maxLen = Math.max(...arr.map(s => s.length)); const result = arr.reduce((pre, curr) => { if (curr.length === maxLen) { pre[curr[0]] = curr.length; } return pre; }, {}); console.log(result);
正则表达式写错了,应该用+,而不是*
/(\w)\1+/g
你考虑到长度最长是一位的情况吗?
抱歉啊。。。考虑欠佳
写一下自己比较low想法,要走的路还很长啊
function handleString(str) {
var obj = {},
arr = [],
returnObj = {};
obj[str[0]] = 1;
for (let a = 1;a < str.length;a++) {
if (str[a] === str[a - 1]) {
obj[str[a]]++;
} else {
obj[str[a]] = 1;
}
}
for (let val in obj) {
if (arr[obj[val]] === undefined || arr[obj[val]].length === 0) {
arr[obj[val]] = [val];
} else {
arr[obj[val]].push(val);
}
}
arr[arr.length - 1].forEach(function(ele) {
returnObj[ele] = arr.length - 1;
})
return returnObj;
}
感觉这个应该是正常人的写法,没有特色,一步一步向下解析 😄
function findLargeNumObj (str = '') {
console.log('***********************************')
console.log(str)
if (!str) {
return {}
}
let result = {}
let newObj = {}
str = str.split('')
let max = 0
// 找一个不重复的数组
let noRepeatArr = [...new Set(str)]
noRepeatArr.forEach((item, index) => {
let isHas = true
let num = 0
let firstIndex = -1 // -1标记没找到
let _z = Array.from(str)
while (isHas) {
if (newObj[item] && newObj[item] < num) {
newObj[item] = num
}
if (_z.indexOf(item) === -1) {
isHas = false
break
} else {
if (firstIndex === -1) {
firstIndex = _z.indexOf(item)
num = 1
newObj[item] = num
} else {
if (_z.indexOf(item) === 0) {
++num
} else {
num = 1
}
firstIndex = _z.indexOf(item)
}
}
_z = _z.slice(firstIndex + 1)
}
})
Object.entries(newObj).forEach(([key, value]) => {
if (value > max) {
max = value
result = {}
result[key] = value
} else if (value === max) {
result[key] = value
}
})
console.log(result)
return result
}
findLargeNumObj ('abcaakjbb');
findLargeNumObj ('abbkejsbcccwqaa');
大家都怎么学的正则表达式啊,我就怕正则
@dyJunZou 干蒙面试官
function getLongest(str) {
let result = {}, mostLength = 1, tempLength = 1
for (let i = 1; i < str.length; i++) {
if (str[i] === str[i - 1]) {
if (++tempLength > mostLength) {
mostLength = tempLength
result = { [str[i]]: mostLength }
} else if (tempLength === mostLength) {
result[str[i]] = mostLength
}
} else {
tempLength = 1
}
}
return result
}
一次循环
function getLongest(str) {
let result = {}, mostLength = 1
str.replace(/(\w)\1+/g, m => {
if (m.length > mostLength) {
mostLength = m.length
result = { [m[0]]: mostLength }
} else if (m.length === mostLength) {
result[m[0]] = mostLength
}
})
return result
}
来一个正则的,思路和上面的差不多
这道题和LeetCode的第三题有点类似,但比它简单多了
leetcode3. 无重复字符的最长子串
function findString(str) {
const strArr = str.split('')
const result = strArr.reduce((acc, cur) => {
acc[cur] ? acc[cur]++ : acc[cur] = 1
return acc
}, {})
console.log(result)
const max = Math.max(...Object.values(result))
let obj = {}
Object.keys(result).forEach(v => result[v] === max ? obj[v] = max : '')
return obj
}
function getMax(str) { let c = ""; let res = Array.from(str).reduce((acc, cur) => { if (c == cur) { acc[cur] = acc[cur] ? acc[cur] + 1 : 2; } else { acc[cur] = 1; } c = cur; return acc; }, {}); let max = Math.max.apply(null, Object.values(res)); let ret = {}; for (let k in res) { if (res[k] == max) { ret[k] = max; } } return ret; } console.log(getMax("abbkejsbcccwqaa")); //{c: 3} console.log(getMax("abcaakjbb")); //{a: 2, b: 2}
acc[cur] = acc[cur] ? acc[cur] + 1 : 2;能否问个问题,:后面为啥是2,还有getMax('ddfe j')中间有空字符的情况要不要考虑
const arr = str.match(/(\w)\1*/g); const maxLen = Math.max(...arr.map(s => s.length)); const result = arr.reduce((pre, curr) => { if (curr.length === maxLen) { pre[curr[0]] = curr.length; } return pre; }, {}); console.log(result);
// TS 版本
interface LooseObject {
[key: string]: any
}
console.log(p104('abcaakjbb'))
console.log(p104('abbkejsbcccwqaa'))
function p104(input: string) {
let regex: RegExp = /(.)\1*/g
let result: Array | null = input.match(regex)
if (!result) {
return {}
}
let maxLen: number = Math.max(...result.map(({ length: len }) => len))
let final: LooseObject = result.reduce((acc: LooseObject, cur) => {
if (cur.length === maxLen) {
acc[cur[0]] = cur.length
}
return acc
}, {})
return final
}
General:
function findMaxLengthOfChars(input) {
let current = "";
let r = [];
Array.from(input).forEach((c, i, a) => {
if (c === a[i - 1]) {
current += c;
}
else {
if (current !== "") {
r.push(current);
}
current = c;
}
if (i === a.length - 1) {
r.push(current);
current = "";
}
});
let output = {};
r = r.sort((t1, t2) => t2.length - t1.length);
r.filter(t => t.length === r[0].length).forEach(t => output[t[0]] = t.length);
return output;
}
function showMaxLengthOfChars(input) {
let json = JSON.stringify(findMaxLengthOfChars(input)).replace(/"/g, "'");
console.log(`'${input}' => ${json}`);
}
showMaxLengthOfChars("abcaakjbb");
showMaxLengthOfChars("abbkejsbcccwqaa");
Use RegExp
:
function findMaxLengthOfChars(input) {
let r = input.match(/(.)\1*/g);
let output = {};
r = r.sort((t1, t2) => t2.length - t1.length);
r.filter(t => t.length === r[0].length).forEach(t => output[t[0]] = t.length);
return output;
}
function showMaxLengthOfChars(input) {
let json = JSON.stringify(findMaxLengthOfChars(input)).replace(/"/g, "'");
console.log(`'${input}' => ${json}`);
}
showMaxLengthOfChars("abcaakjbb");
showMaxLengthOfChars("abbkejsbcccwqaa");
正则
function findMost(s){
let arr = s.match(/([a-z])\1+/g)||[]
if(!arr.length){
return s.split('').reduce((prev,cur)=>{
if(cur === undefined) return
prev[cur] = 1
return prev
},{})
}
let maxVal = 1;
arr.forEach(item=>{
item.length > maxVal ? maxVal = item.length :''
})
return arr.reduce((prev,cur)=>{
cur.length === maxVal ? prev[cur[0]]=maxVal :''
return prev
},{})
}
function strObj(val) {
let res = /(\w)\1+/g;
if (val.match(res) === null){
return new Error('你玩我');
}
let strArr = val.match(res);
let max = 0;
let maxNode = null;
let maxObj = {};
for (let i = 0 ; i < strArr.length ; i++){
if (strArr[i].length > max){
maxObj = {};
max = strArr[i].length;
maxNode = strArr[i].substring(0,1);
maxObj[maxNode] = max;
}
if (strArr[i].length === max){
maxObj[strArr[i].substring(0,1)] = max;
}
}
return maxObj;
}
初学者请多包含,有什么不对的地方,请指出
function getMaxSerial (str) {
const result = {};
let char = str[0];
let count = 1;
let maxCount = 1;
for(var j = 1, length = str.length; j < length; j++) {
if (str[j] === char) {
count++;
} else {
if (maxCount <= count) {
maxCount = count;
if (!result[char]) {
result[char] = count;
} else {
result[char] = Math.max(result[char], count);
}
}
char = str[j];
count = 1;
}
}
if (char === str[length - 1]) {
result[char] = Math.max(result[char], count);
} else {
result[str[length - 1]] = Math.max(result[char], count);
}
return Object.keys(result).reduce((accumulator, key) => {
if (result[key] === maxCount) {
accumulator[key] = result[key];
}
return accumulator;
}, {});
}
'aaasdofjaopfjopaiiisjssfopiasdfffff'.match(/(\w)\1+/g).sort(function(a,b){return b.length-a.length})[0]
function checkMaxLenStr(str) {
let count = 0, max = 0, result = {};
const strArr = str.split('');
for (let i = 0; i < strArr.length - 1; i++) {
count += 1;
if (strArr[i] !== strArr[i + 1]) {
if (Object.keys(result).length === 0) {
max = count;
} else if (count > max) {
max = count
result = {};
}
} else if (i === strArr.length - 2) {
count += 1
}
if (count >= max || Object.keys(result).length === 0) {
result[strArr[i]] = count
}
if (strArr[i] !== strArr[i + 1]) {
count = 0
}
}
return result
}
function findLongest(str){
function merge(){
const key = Object.keys(temp)[0];
if(key && temp[key] > result[key]){
result[key] = temp[key]
}
}
const result = {}
let target = str[0]
let temp = {}
for(let item of str){
if(result[item]){
if(item === target){
temp[item] ? temp[item]++ : result[item]++
} else {
if(temp[item]){
temp[item]++
} else {
temp[item] = 1
}
}
} else {
merge();
temp = {}
result[item] = 1
}
target = item
}
merge();
console.log(result)
}
注:以下方法暂时还有缺陷,"abcaakjbb"只能输出a : 2,后面的b统计不了,当一个字符串中只有一个字符数量最多的情况下是可以正确统计的,而且这个还支持统计一句话中出现数量最多的字符及个数。
let str = '';
str = "abbkejsbcccwqaa";
// str = "abcaakjbb";
// str = "this is a very important day";
let num = 0;
let value = null;
function counter() {
let new_str = '';
new_str = str.replace(/\s+/g, '');
var reg = /(\w)\1+/g;
//$0代表取出来重复的一个个整体,如[b,b],[c,c,c],$1代表这个整体里的字符
new_str.replace(reg,function($0,$1){
if(num < $0.length) {
num = $0.length;
value = $1;
}
});
console.log(value+" : "+num) // c : 3
};
counter();
function maxCount(str) {
let length = str.length;
let i = 0,
result = {};
while (i < length) {
let num = 1;
for (let j = i + 1; j < length; j++) {
if (str[i] != str[j]) {
break;
}
num++;
}
result[str[i]] = num
i += num;
}
let value = Math.max(...Object.values(result))
for (let item in result) {
if (result[item] != value) {
delete result[item]
}
}
return result
}
console.log(maxCount("aaasssdd"))
说一下自己的解题思路:
1、遍历这个字符串,记录每个元素重复出现的次数,如果没有重复出现的,那个字符出现的次数就是1
2、找出出现次数最大的元素数目
3、匹配元素(因为可能有2个以上相同数目的最大数,所以我是采用删除原对象中不匹配的属性的方法)
function findRep (string) {
const res = string.match(/(\w)(\1+)?/g);
const len = Math.max(...res.map(e => e.length));
return res.filter(e => e.length === len).reduce((red, e) => end[e[0]] = e.length, {})
}
console.log(findRep('abbkejsbcccwqaa')) // {c:3}
console.log(findRep('abbkejsbccwq')) // {b:2, c: 2}
console.log(findRep('abcac')) // {a:1, b:1, c: 1}
看了很多大佬的回答后优化下 匹配最大数目属性
function maxCount(str) {
let length = str.length;
let i = 0,
result = {};
while (i < length) {
let num = 1;
for (let j = i + 1; j < length; j++) {
if (str[i] != str[j]) {
break;
}
num++;
}
result[str[i]] = num
i += num;
}
let max = Math.max(...Object.values(result))
// 优化了这里
let entries = Object.entries(result).filter(function([_,value]){
return value == max
})
return entries
}
console.log(maxCount("acdfvg"))
function findRepeatMaxChar(str) {
const strArr = str.match(/([^\s])\1*/g);
const maxLen = Math.max(...strArr.map(it => it.length));
return strArr.reduce((prev, cur) => {
cur.length === maxLen && (prev[cur[0]] = cur.length);
return prev;
}, {});
}
console.log(findRepeatMaxChar('abcaakjbb'));
console.log(findRepeatMaxChar('abbkejsbcccwqaa'));
console.log(findRepeatMaxChar('aabbccddccbbaa'));
console.log(findRepeatMaxChar(' a bb cc '));
console.log(findRepeatMaxChar('a'));
var array = ['abcaakjbb' , 'abbkejsbcccwqaa'] ;
var reg=/(.)\1+/ig;
//获取匹配到的重复的字符串或符号:
var str_match =array[1].match(reg);
console.log(str_match);
console.log(getMaxCount(str_match,result={}));
function getMaxCount( str , result={}){
// 求最长的数值
for ( i=0;i<str.length;i++ ) {
if (str[i].length > maxlength){
maxlength=str[i].length;
}
}
// 匹配答案
for (index in str){
if(str[index].length===maxlength){
result[str[index].substring(0,1)]=maxlength;
}
}
return result;
}
ZBMAC-C02VX3K0H:USER$
[ 'bb', 'ccc', 'aa' ]
maxlength:3
index:1
{ c: 3 }
function find(str){
let Obj={};
str.split('').reduce((o,p,index)=>{
o===p?(Obj[o]?Obj[o]=Obj[o]++:Obj[o]=2):null
return p
});
Object.keys(Obj).forEach(k=>{
if(Obj[k]!==Math.max(...Object.values(Obj))){
delete Obj[k]
}
});
return Obj;
}
看不懂
一开始不知道用元字符,写出来这么长一大串:
function get(str) {
let res = Object.create(null), max = 0
for(let i = 0; i < str.length; i++) {
let ch = str[i],
reg = new RegExp(`(${ch}+)`, 'g')
if (!res[ch]) {
str.replace(reg, (m, $0) => {
if (res[ch] < $0.length) {
res[ch] = $0.length
if (max <= $0.length) max = $0.length
}
return $0
})
}
}
Object.keys(res).forEach(key => {
if (res[key] < max) {
delete res[key]
}
})
return res
}
用了元字符以后还是简短了很多的:
function getWithMeta(str) {
let reg = /(\S)\1*/g, res = {}, max = 0
str.replace(reg, (m, $0) => {
res[$0] = res[$0] ? (res[$0] < m.length ? m.length : res[$0]) : m.length
if (m.length > max) max = m.length
})
Object.keys(res).forEach(k => {
if (res[k] < max) delete res[k]
})
return res
}
function MRC(str) {
str = str + "$";
let count = (max = 1);
let maxKeys = [str[0]];
for (let i = 0; i < str.length; i++) {
const pre = str[i - 1];
if (str[i] === str[i - 1]) {
count++;
} else {
if (count > max) {
maxKeys = [pre];
max = count;
} else if (count === max) {
maxKeys.push(pre);
}
count = 1;
}
}
return maxKeys.reduce((acc, k) => (acc[k] = max, acc), {});
}
function maxChildStr(str) {
const map = new Map();
let len = 0;
str.match(/(\S)\1*/g).forEach(data => {
const o = data.charAt(0);
// map长度为0 或者 有更大子串出现
if (!map.size || data.length > len) {
map.delete(len);
len = data.length;
map.set(len, Object.create(null));
}
// 仅存储不小于当前的最大子串长度的
if (data.length >= len) {
map.get(len)[`${o}`] = len;
}
});
return map.get(len);
}
// test
const a = 'aqbcakjb',
b = 'abbkejsbcccwqaa';
console.time();
console.log('a的最大子串', maxStr(a))
console.log('b的最大子串', maxStr(b))
console.timeEnd();
'aaasdofjaopfjopaiiisjssfopiasdfffff'.match(/(.)\1+/g)得到的结果是
["aaa", "iii", "ss", "fffff"]从这个数组里面找长度最长的元素并转化成需要的结果应该简单了吧
太强了
function func(str) {
const arr = str.match(/(.)\1*/g).sort((a,b)=>b.length - a.length)
const result = {}
arr.forEach(item=>{
if(item.length > 1) {
result[item[0]] = item.length
}
})
return result
}
var str = "11223344555666677778888";
var aa = str.match(/(.)\1*/g)
var a={},b=0;
aa.forEach(function(v,i){
if(v.length==b){
a[v[0]]=v.length;
b=v.length;
}else if(v.length>b){
a={};
a[v[0]]=v.length;
b=v.length;
}
})
console.log(a);
let moreChat = str => {
let char = null ; // 记录上一个字符是否和本地循环的字符一样
let charNum = 0 ; // 记录当前字符连续出现的次数
let max = 0 ; // 记录出现字符最多的次数
let res = {} ; // 返回结果
for(let i = 0 ; i < str.length ; i++){
if(str[i] === char){
charNum ++ ;
if(i === str.length - 1){
if( charNum > max ){
max = charNum ;
res = {[char]:charNum} ;
}else if(charNum === max){
res[char] = charNum ;
}
}
}else{
if( charNum > max ){
max = charNum ;
res = {[char]:charNum} ;
}else if(charNum === max){
res[char] = charNum ;
}
char = str[i] ;
charNum = 1 ;
}
}
return res ;
}
let a = 'abcaakjbb' ; //{a:2,b:2};
let b ='abbkejsbcccwqaaddd';
//菜鸟中的菜鸟版
function checkMaxAlpha(params){
let tmp = {}; //{2:[a,b]}
let pre = "";
for(var i= 0;i<params.length;i++){
var current = params.charAt(i);
if(current == pre){ //进行计数
if(tmp[current]){
tmp[current] = tmp[current] + 1;
}else{
tmp[current] = 2;
}
}
pre = current;
}
let keys = Object.keys(tmp);
let maxKey = keys[0];
for(var j = 1; j<keys.length;j++){
let currentKey = keys[j];
if(tmp[maxKey]<tmp[currentKey]){
delete tmp[maxKey];
maxKey = currentKey;
}else if(tmp[maxKey] > tmp[currentKey]){
delete tmp[currentKey];
}
}
return tmp;
}
console.log(checkMaxAlpha(a),checkMaxAlpha(b));
var foo = 'asdsdeasded'.split('').reduce(function (sum, item, idx) {
let row = sum[item] || 0
sum[item] = row + 1
return sum
}, {})
var max = Math.max(...Object.values(foo))
var baz = {}
Object.keys(foo).map(item => {
if (foo[item] == max) {
baz[item] = max
}
})
console.log(baz)
不用正则,不用 Math.max,不用 split,强行一行搞定。(看得懂才见鬼)
Object.values([...'abcaakjbb']
.reduce((a, b, c, d) => b === d[c - 1] && (a[c] = [b, a[c - 1] ? a[c - 1][1] + 1 : 2]) && a || a, {}))
.reduce((a, b) => (c = b[1] - (Object.values(a)[0] || 0)) & (c > 0 && (a = {})) & (c >= 0 && (a[b[0]] = b[1])) || a, {})
var foo = 'asdsdeasded'.split('').reduce(function (sum, item, idx) { let row = sum[item] || 0 sum[item] = row + 1 return sum }, {}) var max = Math.max(...Object.values(foo)) var baz = {} Object.keys(foo).map(item => { if (foo[item] == max) { baz[item] = max } }) console.log(baz)
很明显忽略了连续这个条件
const findStr = str => {
const strMap = Array.from(str).reduce((pre, cur, index, arr) => {
if (!pre[cur]) {
pre[cur] = 1;
}
if (index >= 1 && cur !== arr[index - 1]) {
pre[cur] = 0;
}
pre[cur]++;
return pre;
}, {});
return strMap;
};
const ret = findStr("abcaakjbb");
const max = Math.max(...Object.values(ret));
const maxVal = Object.entries(ret).filter(item => item[1] === max);
let obj = {};
maxVal.forEach(item => {
obj[item[0]] = item[1];
});
console.log(obj);
function findRepeatString(str) {
let result = {};
let temp = str[0];
let count = 1; // 累加计数
let max = 0; //连续字符出现次数最大值
for (let i = 1; i < str.length; i++) {
if (temp === str[i]) {
count++;
if (count >= max) {
result = count > max ? {} : result;
result[temp] = count;
max = count;
}
} else {
// 不等时重置零时变量和计数
count = 1;
temp = str[i];
}
}
return result;
}
console.log(findRepeatString('abbbkejsbcccwqaa'));
// 编程题,找出字符串中"连续"出现最多的字符和个数
// 'abbkejsbcccwqaa' => {c: 3}
let strs = "abbkejsbcccwqaa";
let maxKey = "",
count = 0,
prevStr = "",
prevCount = 0,
curStr = "";
function getResult(str) {
str += " ";
for (let i = 0; i < str.length; i++) {
curStr = str.substring(i, i + 1);
prevCount++;
if (curStr != prevStr) {
if (prevCount >= count) {
maxKey = prevStr;
count = prevCount;
}
prevCount = 0;
}
prevStr = curStr;
}
}
getResult(strs)
console.log({ [maxKey] : count});
//找出字符串中重复一次及以上的 并以对象形式返回 如'aabcccd' >>> {'a':2 , 'c':3}
const find = (str)=> {
let res = {};
const toArr = str.split('');
[...new Set(toArr)].map(it=>{
const num = toArr.filter(n=> n === it).length;
if(num>1){
res[it] = num;
}
});
return res
}
function finLongestStr(str){
if(!str) return '请传入内容';
let arr = str.split('');
let obj = {},m=1,max = 1,maxObj = {};
for(let i=0;i<arr.length;i++){
for(let j=0;j<arr.length;j++){
if(arr[i] == arr[j]){
obj[arr[i]] = m;
m++;
}
if(j == arr.length-1){
if(m-1 >= max){
max = m -1;
maxObj[arr[i]] = max;
}
m = 1;
}
}
}
return maxObj
}
function finLongestStr(str){ if(!str) return '请传入内容'; let arr = str.split(''); let obj = {},m=1,max = 1,maxObj = {}; for(let i=0;i<arr.length;i++){ for(let j=0;j<arr.length;j++){ if(arr[i] == arr[j]){ obj[arr[i]] = m; m++; } if(j == arr.length-1){ if(m-1 >= max){ max = m -1; maxObj[arr[i]] = max; } m = 1; } } } return maxObj }
function findRepeatString(str) {
let result = {};
let temp = str[0];
let count = 1; // 累加计数
let max = 0; //连续字符出现次数最大值for (let i = 1; i < str.length; i++) {
if (temp === str[i]) {
count++;
if (count >= max) {
result = count > max ? {} : result;
result[temp] = count;
max = count;
}
} else {
// 不等时重置零时变量和计数
count = 1;
temp = str[i];
}
}return result;
}
我试了下,运行结果不对,count少了一个
'''js
function matchCount(str, letter) {
const reg = new RegExp(${letter}
, 'g')
const matchArr = str.match(reg)
// console.log(matchArr, reg)
return matchArr.length
}
console.log(matchCount('adsadasdasdadsas', 'a'))
'''
上面的理解错了
function matchCount(str) {
if (typeof str === 'string') {
const strArr = str.split('')
const map = {}
let tick = 1
for (let i = 1; i < strArr.length; i++) {
const s = strArr[i]
map[s] = map[s] || 1
if (strArr[i - 1] === strArr[i]) {
tick +=1
map[s] = map[s] > tick ? map[s] : tick
} else {
tick = 1
}
}
let maxKey = null
for (const key in map) {
if (!maxKey) {
maxKey = key
} else if (map[maxKey] > map[key]) {
delete map[key]
} else if(map[maxKey] < map[key]) {
delete map[maxKey]
maxKey = key
}
}
return map
}
return {}
}
console.log(matchCount('adsadassssddddasddadsas'))
function statisticsNumber(str,newArr=[[]]){
let maxNumber = str.split('')
.reduce((pre,value,index)=>( ~pre[pre.length-1].indexOf(value) ? pre[pre.length-1].push(value) : pre.push([value]),newArr),newArr)
.map(item=>item.length).sort((a,b)=>b-a).shift() , newObj={}
newArr.forEach(item=>{
item.length===maxNumber && (newObj[item[0]]=maxNumber)
})
return newObj
}
一次遍历
function findLongest(str) { if (!str) return {} let count = 0 let maxCount = 0 let cur = str[0] let res = {} for (let i = 0; i < str.length; i++) { const s = str[i] if (s === cur) { count++ if (count > maxCount) { res = { [s]: count } maxCount = count } if (count === maxCount) { res[s] = count } } else { count = 1 cur = s } } return res }时间复杂度O(n), 空间复杂度O(1)
你这个 输入 ab 返回 {a:1}
function count(str) {
if (!str) return {};
let hashMap = {};
let i = 1;
let cur = str[0];
for (let j = 1; j < str.length; j++) {
let temp = str[j];
if (temp === cur) {
i++;
hashMap[temp] = i;
} else {
i = 1;
cur = temp;
}
}
let res = Object.keys(hashMap).map(key => hashMap[key]);
res = Math.max(...res);
for (let key in hashMap) {
if (hashMap[key] < res) {
delete hashMap[key]
}
}
return hashMap
}
/*
第 114 题:编程题,找出字符串中连续出现最多的字符和个数(蘑菇街)
'abcaakjbb' => {'a':2,'b':2}
'abbkejsbcccwqaa' => {'c':3}
*/
function sequenceChar(str){
const chars = str.split('');
let count = 0;
let max = 0
let res = {};
chars.reduce((pre,cur,index)=>{
if(pre===cur){
count++;
if(count>max){
res = {[pre]:count}
max = count;
}
if(count === max){
res[pre] = count;
}
}else{
count=1;
res[pre] = 1;
if(index===chars.length-1){
res[chars[index]] = count;
}
}
return cur;
});
return res;
}
console.log(sequenceChar('abkejsbcwqa'));
function getMaxStr(str) {
let map = {}
let resultArr = []
let max = Number.NEGATIVE_INFINITY
let k = 1
for (let i = 1; i < str.length; i++) {
if (str[i] == str[i-1]) {
k++
if (k > max) {
resultArr = [str[i]]
}
if (k == max) {
resultArr.push(str[i])
}
// max = k
max = Math.max(k, max)
} else {
k = 1
}
}
console.log(resultArr, max)
for (let i = 0; i < resultArr.length; i++) {
map[resultArr[i]] = max
}
return map
}
function findNum(str){
let res = {};
let num = 1;
let max = num;
for(let i=0;i<str.length;i++){
if(str[i+1] === str[i]){
num++;
} else {
if(num>max){
res = {};
res[str[i]] = num;
max = num;
num = 1;
} else if(num === max){
res[str[i]] = num;
num = 1;
}
}
}
return res;
}
const data = 'abbkejsbcccwqaaaa';
console.log(findNum(data));
一次遍历完成,复杂度O(n)
// 编程题,找出字符串中 **连续** 出现最多的字符和个数(蘑菇街)
const str1 = 'abcaakjbb'
const result1 = { a: 2, b: 2 }
const str2 = 'abbkejsbcccwqaa'
const result2 = { c: 3 }
function findMax(str) {
let map = {}
let pre = ''
let preLen = 0
let cur = ''
let curLen = 0
for (let i = 0; i < str.length; i++) {
const s = str[i]
const next = str[i + 1]
if (s === next) {
cur = s
curLen = curLen ? ++curLen : 2
} else {
if (curLen > preLen) {
if (pre === cur) {
preLen = curLen
map[cur] = curLen
} else {
map = {
[cur]: curLen
}
pre = cur
preLen = curLen
}
}
if (curLen === preLen) {
if (pre !== cur) {
map[cur] = curLen
}
}
cur = ''
curLen = 0
}
}
console.log(map)
return map
}
const find1 = findMax(str1)
console.log(JSON.stringify(find1) === JSON.stringify(result1))
const find2 = findMax(str2)
console.log(JSON.stringify(find2) === JSON.stringify(result2))
'aaasdofjaopfjopaiiisjssfopiasdfffff'.match(/(.)\1+/g)得到的结果是
["aaa", "iii", "ss", "fffff"]从这个数组里面找长度最长的元素并转化成需要的结果应该简单了吧
可以简化很多计算量!