字符串中连续最多的字符&次数
双层for循环
const repeatStrAndNumsByDoubleLoop = (str = 'aabbbcccddeeefffff') => { const res = { char: '', len: 0 } const { length } = str for(let i = 0; i < length; i++){ let charLen = 1 const curValue = str[i] for(let j = i + 1; j < length; j++){ const nextValue = str[j] if(curValue === nextValue){ charLen += 1 } if(curValue !== nextValue || j === length - 1){ if(charLen > res.len){ res.char = curValue res.len = charLen } i = j - 1 // 进行跳步 减少时间复杂度 break } } } return res }
双指针
const repeatStrAndNumsByDoublePointer = (str = 'aabbbcccddeeefffff') => { const res = { char: '', len: 0 } const { length } = str if (!length) { return res } if(length === 1){ return { char:str, len: 1 } } let fixedIndex = 0 let len = 1 for(let i = 1; i < length; i++){ const value = str[i] if(value === str[fixedIndex]){ len++ } if(value !== str[fixedIndex] || i === length - 1) { if(len > res.len){ res.len = len res.char = str[i - 1] } fixedIndex = i len = 1 } } return res }
以自己现在的努力程度,还没有资格和别人拼天赋