题目:给一个字符串,找出连续最多的字符,以及次数。如:'aabbcccddeeee112233' 连续最后的是e ,4次
分析:
- 传统方式,嵌套循环
- 嵌套循环,找出每个字符的连续次数,并记录比较
- 时间复杂度:因为是嵌套循环,所以看似是O(n^2), 但因为循环中有跳转,所以实际上它是O(n)
- 双指针
- 定义指针 i 和j
- j 不动,i 循环移动
- 如果 i和j 值一直相等,i 继续移动
- 如果i 和 j 值不相等,记录处理。让j 追上i 。继续下一步
- 时间复杂度: O(n)
代码实现:
- 嵌套循环 O(n)
/*** @description 连续最多的字符以及次数*/ interface IRes {char: string,length: number } /*** 连续最多的字符以及次数 -- 嵌套循环* @param str * @returns */ export function findContinuousChar1 (str: string): IRes{const res: IRes = {char: '',length: 0}const length = str.lengthif(length === 0 ){return res}for(let i = 0; i < length; i++){const temp = str[i]let tempLength = 1for(let j = i + 1; j < length; j++){if(temp === str[j]){tempLength++}//不想等 或者 到了最后一个元素仍想等的时候也需要处理if(temp !== str[j] || j === length -1){if(tempLength > 1 && tempLength > res.length){res.char = tempres.length = tempLength}i = j-1 //跳步,下一次循环从j开始。因为下一次循环i会再加1,所以此处i赋值为 j-1break}}}return res }
- 双指针 O(n)
/*** 连续最多的字符以及次数 -- 双指针* @param str * @returns */
interface IRes {char: string,length: number }
export function findContinuousChar2 (str: string): IRes{const res: IRes = {char: '',length: 0}const length = str.lengthif(length === 0) return reslet i = 0let j = 0let temlength = 0for(; i < length; i++){if(str[i] === str[j]){temlength++}// 不想等 或者 到最后一个元素仍想等的情况 if(str[i] !== str[j] || i === length -1){if(templength > 1 && temlength > res.length){res.char =str[j]res.length = temlength}if(i < length -1){j = i //让 j 追上 ii-- // 下一次循环 i会加1,所以这里要一1 }temlength = 0}}return res }
测试用例:
/*** @description 连续最多的字符以及次数测试*/ import {findContinuousChar1,findContinuousChar2} from './continuous-char' describe('连续最多的字符以及次数',()=>{it('正常数据',()=>{const res = findContinuousChar1('aabbcccddeeee112233');const res2 = findContinuousChar2('aabbcccddeeee112233');expect(res).toEqual({char:'e',length: 4})expect(res2).toEqual({char:'e',length: 4})})it('空字符串',()=>{const res = findContinuousChar1('');const res2 = findContinuousChar2('');expect(res).toEqual({char:'',length: 0})expect(res2).toEqual({char:'',length: 0})})it('无连续符串',()=>{const res = findContinuousChar1('abcedrg');const res2 = findContinuousChar2('abcedrg');expect(res).toEqual({char:'',length: 0})expect(res2).toEqual({char:'',length: 0})})it('全是连续字符',()=>{const res = findContinuousChar1('aaaaaa');const res2 = findContinuousChar2('aaaaaa');expect(res).toEqual({char:'a',length: 6})expect(res2).toEqual({char:'a',length: 6})}) })