Fe-interview: [js] 第105天 写个方法,找出指定字符串中重复最多的字符及其长度

Created on 29 Jul 2019  ·  31Comments  ·  Source: haizlin/fe-interview

第105天 写个方法,找出指定字符串中重复最多的字符及其长度

js

Most helpful comment

function findMaxLetter (str) {
  let maxLetter = ''
  let maxLen = 0
  let key = {}
  str.split('').forEach(item => {
    if (key[item] === undefined) {
      key[item] = 1
    } else {
      key[item]++
    }
    if (key[item] > maxLen) {
      maxLen = key[item]
      maxLetter = item
    }
  })

  return [maxLetter, maxLen]
}

All 31 comments

let cfStr = str => {
    let num = 0;
    let cfs = str[0];
    for (var i = 0; i < str.length; i++) {
        num = num > str.split(str[i]).length - 1 ? num : str.split(str[i]).length - 1
        cfs = num > str.split(str[i]).length - 1 ? cfs : str[i]
    }
    return '重复次数:' + num + '重复字符串:' + cfs
}
function maxOccurence(str) {
    const dict = {}
    for (const char of str) {
        if (char in dict) dict[char]++
        else dict[char] = 1
    }
    let maxchar = [], maxcount = -1
    for (const char in dict)
        if (dict[char] === maxcount) maxchar.push(char)
        else if (dict[char] > maxcount) {
            maxchar = [char]
            maxcount = dict[char]
        }
    return { char: maxchar, count: maxcount }
}

注意到可能出现多种字符出现次数相等的特殊情况,所以采用数组存储结果;
返回值需要语义化,所以返回一个对象 { char: string[], count: number }

function test(str){
    let _length = 0;
    let word = '';
    let result = []
    let str_list = str.split('');
    let _result = new Set(str_list);
    for(let w of _result){
        let number = str_list.filter(element => element == w).length;
        if(number > _length){
            result = [{
                              _length: number,
                              word: w
                         }]
            _length = number;
        }else if(number == _length){
            result.push({
                             _length: number,
                             word: w
                        })
        }
    }
    return result;
}
function test(str){
  if(!str || str.length <=1){
    return str
  }
  var dict = {

  }
  for(var i = 0; i< str.length; i++){
//     console.log(i)
    if(dict[str[i]]){
      dict[str[i]] += 1
    } else {
      dict[str[i]] = 1
    }
  }
  var max = 0
  var char = ''
  for(i in dict){
    console.log(i)
    if(dict[i] > max){
      max = dict[i]
      char = i
    }
  }
  console.log(dict, char, max)
}

test('aaaaccksksks')
function findMaxLetter (str) {
  let maxLetter = ''
  let maxLen = 0
  let key = {}
  str.split('').forEach(item => {
    if (key[item] === undefined) {
      key[item] = 1
    } else {
      key[item]++
    }
    if (key[item] > maxLen) {
      maxLen = key[item]
      maxLetter = item
    }
  })

  return [maxLetter, maxLen]
}
function test(str){
  let l = str.length;
  let map = new Map(),rett=[]
  for(let i  = 0 ;i<l;i++)
  {
    if(!map.has(str[i]))
    {
      map.set(str[i],1)
    }
    else
    {
        map.set(str[i],map.get(str[i])+1)
    }
  }
    let temp = map.values(),max=0;
    for(i of temp)
        {
            if(i>max)
                {max=i}
        }
    for(i of map)
        {
            if(i[1]==max)
                {
                    rett.push([i[0],max])
                }
        }
  return rett
}

第105天 写个方法,找出指定字符串中重复最多的字符及其长度

@haizhilin2013

找出重复次数最多的 子串 及其长度?

找出重复次数最多的字符及其重复次数

@liuxiaole

找出重复次数最多的 子串 及其长度?

找出重复次数最多的字符及其重复次数

找出重复次数最多的字符,及其所组成的子序列的长度。

@t532

@liuxiaole

找出重复次数最多的 子串 及其长度?
找出重复次数最多的字符及其重复次数

找出重复次数最多的字符,及其所组成的子序列的长度。

没明白。以 abcabcaca为例子,要找重复最多的什么?以及什么的长度?

没明白。以 abcabcaca为例子,要找重复最多的什么?以及什么的长度?

对于串 𝑆:
设其中出现的所有字符为集合 𝐶;
∀ 𝑐 ∈ 𝐶, 𝑛𝑐 ⟵ 𝑐 在 𝑆 中出现的次数;
求 𝘮𝘢𝘹(𝑛𝑐) 及对应的字符集合 𝐾。

对于 abcabcaca,𝘮𝘢𝘹(𝑛𝑐) = 4,𝐾 = { a }。

那不就是求出现次最多的字符和次数吗?哪有长度的概念?

t532 notifications@github.com 于 2019年7月30日周二 17:31写道:

@liuxiaole https://github.com/liuxiaole

没明白。以 abcabcaca为例子,要找重复最多的什么?以及什么的长度?

对于串 𝑆,设其中出现的所有字符为集合 𝐶,对于所有 𝑐 ∈ 𝐶,记 𝑐 在 𝑆 中出现的次数为 𝑛𝑐,求 𝘮𝘢𝘹(𝑛𝑐)
及对应的字符集合 𝑘。

对于 abcabcaca,𝘮𝘢𝘹(𝑛𝑐) = 4,𝑘 = { a }。


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/haizlin/fe-interview/issues/1003?email_source=notifications&email_token=AAUXUFUJFN2OJ5ZTX7L65YDQB7G25A5CNFSM4IHWAJVKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD3C2E2Q#issuecomment-516268650,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAUXUFSGEJMXQ46FSJXBCFDQB7G25ANCNFSM4IHWAJVA
.

那不就是求出现次最多的字符和次数吗?哪有长度的概念?

可以表述为:∀ 𝑘 ∈ 𝐾,𝑆 中仅包含 𝑘 的子序列(Subsequence)的长度。它与 𝘮𝘢𝘹(𝑛𝑐) 等价。

我的理解是”重复最多的字符及其长度”,“其”指代的是前面提到的字符,等价于“及该字符的长度”,而字符长度为1,所以比较困惑。如果按照大家的解答,题目完全应该表述为“及重复的次数”。如果要强行按子序列的长度解释,那应该为“及由这些重复字符组成的子序列的长度”,显然还是在求重复的次数,没必要引进子序列然后求长度。

t532 notifications@github.com 于 2019年7月30日周二 17:42写道:

@liuxiaole https://github.com/liuxiaole

那不就是求出现次最多的字符和次数吗?哪有长度的概念?

可以表述为对于每个 𝑘 ∈ 𝐾,𝑆 中仅包含 𝑘 的子序列(Subsequence)的长度。它与 𝘮𝘢𝘹(𝑛𝑐) 等价。


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/haizlin/fe-interview/issues/1003?email_source=notifications&email_token=AAUXUFU4VPEUHLG4MORFDQDQB7ID7A5CNFSM4IHWAJVKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD3C2XKY#issuecomment-516271019,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAUXUFSYQDZ4RDG3N625HBTQB7ID7ANCNFSM4IHWAJVA
.

@liuxiaole

我的理解是”重复最多的字符及其长度”,“其”指代的是前面提到的字符,等价于“及该字符的长度”,而字符长度为1,所以比较困惑。如果按照大家的解答,题目完全应该表述为“及重复的次数”。如果要强行按子序列的长度解释,那应该为“及由这些重复字符组成的子序列的长度”,显然还是在求重复的次数,没必要引进子序列然后求长度。

那是题目表述不当,我无能为力。如果你认为我的解释不对,或许你可以理解为在 UTF-8 编码环境(或其他变长编码环境)下该字符占的字节数。

function find (parent) {
let num = 0;
let i = 0;
for(;i num = num>parent.split(parent[i]).length - 1?num:parent.split(parent[i]).length - 1;
}
return '重复次数:' + num + '重复字符串:' + parent[i-1]
};

@liuxiaole 以abcabcaca为例,a出现4次,b出现2次,c出现3次,所以出现最多的字符是a,它的长度为4

@liaofangyuan 你这个输出重复字符串的位置有错误,应该放在循环里面

@lcs1998 你放进去试试

@liaofangyuan 你这样输出的字符永远是字符串的最后一个,显然不对,应该放在循环里面做个判断,看看是不是最长的,然后再做赋值。
而且你这个也没有考虑有两个字符的重复度相等的情况。

@lcs1998 期待你的答案

@lcs1998 期待你的答案

参考我的,谢谢哎

@NicholasBaiYa
不看看都不知道还能用split来做,不错!但没必要重复split吧?,可读性也不好。不妨把值存起来:

function test (str) {
  let maxLen = 0;
  let char = '';

  for (let i = 0; i < str.length; i++) {
    const d = str[i];
    const len = str.split(d).length - 1;

    if (len > maxLen) {
      maxLen = len;
      char = d;
    }
  }

  return [char, maxLen];
}

@NicholasBaiYa
不看看都不知道还能用split来做,不错!但没必要重复split吧?,可读性也不好。不妨把值存起来:

function test (str) {
  let maxLen = 0;
  let char = '';

  for (let i = 0; i < str.length; i++) {
    const d = str[i];
    const len = str.split(d).length - 1;

    if (len > maxLen) {
      maxLen = len;
      char = d;
    }
  }

  return [char, maxLen];
}

str 要是全部都是相同字符,比如 1 万个 a,那性能要爆炸啊。还是最朴素的用字符当 key 进行统计的方法比较稳定。扫一遍 string,再遍历一遍得到的 map,O(n) 的复杂度。split 操作隐含了 O(n) 复杂度。

楼上的思路都很妙啊,下面是根据我的习惯封装的

>
function findTargetChar(str) {
let maxStr = null;
let maxLength = 0;
let obj = {}
let re = null
if (typeof str === 'string' && str.length > 0) {
str.split('').forEach((ele, index) => {
if (obj[ele] === undefined) {
obj[ele] = 1;
} else {
obj[ele] += 1;
}
if (obj[ele] > maxLength) {
maxLength = obj[ele]
maxStr = ele
}
})
re = [maxStr, maxLength]
}
return re
}

/**
 * 写个方法,找出指定字符串中重复最多的字符及其长度
 */
function searchStr (str) {
  const arr = (str.split('').sort().join('').match(/(.)\1+/g) || []).sort((a, b) => a.length - b.length)
  if (arr.length) {
    const last = arr[arr.length - 1]
    const char = last[0]
    const size = last.length
    return {char, size}
  }
  return undefined
}
console.log(searchStr('asdfaaaaccksksks')) // {char: 'a', size: 5}
function test (str) {
  const listData = {}
  const arr = str.split('')

  for (let i of arr) {
    if (listData[i]) {
      listData[i] ++
    } else {
      listData[i] = 1
    }
  }

  let maxValue = 0
  let maxProps = []
  for(let [k, v] of Object.entries(listData)) {
    if (v === maxValue) {
      maxProps.push(k)
    }

    if (v > maxValue) {
      maxValue = v
      maxProps = [k]
    }
  }

  console.log('maxProps', maxProps)
  console.log('maxValue', maxValue)
}
test('abcde aafgff')

function searchString(str) {
  let arr = str.split('');
  let max = 0;
  let res = [];
  let list = arr.reduce((prev, cur) => {
    if(prev[cur] == undefined) {
      prev[cur] = 1
    } else {
      prev[cur] += 1;
    }
    return prev;
  }, {});
  for(i in list) {
    if(list[i] > max) {
        max = list[i];
        res = [];
        res.push(i);
    } else if(list[i] == max) {
        res.push(i);
    }
  }
  console.log(list);
  console.log(res);
  console.log(max);
}
searchString('idajweoicjxzkljsaoiuwoeunhdjkashdoaiujewqo');
//
const str = "啦啦啦哈哈哈哈";
let result = {}; // 存放全部的结果集的数组

function test1(box = []){
  // 转换数组
  let array = str.split("");
  array.forEach(v => {
    if(typeof result[v] === "undefined"){
      // 添加对应的属性
      result[v] = 1;
    }else{
      result[v] ++;
    }
  })
}


test1();
console.log(result);
function findRepeatStr(str) {
    var obj = {}

  for (var i in str) {
    if (obj[str[i]]) {
      obj[str[i]]++
    } else {
        obj[str[i]] = 1
    }
  }

  var arr = []
  for (var key in obj) {
    arr.push({key:key, num: obj[key]})
  }

  return arr.sort(function (a,b) {
        return b.num-a.num
  })[0]
}

findRepeatStr('aaaabbbbbbbbaasdasdasaa')

`//思路:首先对数组去重然后统计每个字符的个数最后输出最多的
const computeMaxRepeat = (s) => {
if (!typeof s === "string") return;

const keys = Array.from(new Set(s.split("")));
let values = new Array(keys.length).fill(0);
let max = values;

for (let i = 0; i < s.length; i++) {
const index = keys.indexOf(s[i]);
index > 0 ? (values[index] += 1) : null;
}

max = Math.max.apply(Array, values);

return keys[values.indexOf(max)].repeat(max) + " " + max; // aaa 3;
};

const str = "bcaaammo";
console.log(computeMaxRepeat(str));
`

    const str = 'apple, banana';
    function fintMost(str) {
      const obj = {};
      let mostLen = 0;
      let mostStr = '';
      for (let index = 0; index < str.length; index++) {
        if (obj.hasOwnProperty(str[index])) {
          obj[str[index]] += 1;
          continue;
        }
        obj[str[index]] = 1;
      }
      for (const key in obj) {
        if (obj[key] > mostLen) {
          mostLen = obj[key];
          mostStr = key;
        }
      }
      return `最多的字符为${mostStr},次数为${mostLen}`
    }
    const res = fintMost(str);
Was this page helpful?
0 / 5 - 0 ratings