Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
haizhilin2013 opened this issue Jul 29, 2019 · 32 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

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

@haizhilin2013 haizhilin2013 added the js JavaScript label Jul 29, 2019
@NicholasBaiYa
Copy link

NicholasBaiYa commented Jul 30, 2019

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
}

@ghost
Copy link

ghost commented Jul 30, 2019

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 }

@jacob-lcs
Copy link

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;
}

@tiyunchen
Copy link

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')

@xxf1996
Copy link

xxf1996 commented Jul 30, 2019

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]
}

@LinStan
Copy link

LinStan commented Jul 30, 2019

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
}

@liuxiaole
Copy link

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

@haizhilin2013

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

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

@ghost
Copy link

ghost commented Jul 30, 2019

@liuxiaole

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

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

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

@liuxiaole
Copy link

@t532

@liuxiaole

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

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

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

@ghost
Copy link

ghost commented Jul 30, 2019

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

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

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

@liuxiaole
Copy link

liuxiaole commented Jul 30, 2019 via email

@ghost
Copy link

ghost commented Jul 30, 2019

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

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

@liuxiaole
Copy link

liuxiaole commented Jul 30, 2019 via email

@ghost
Copy link

ghost commented Jul 30, 2019

@liuxiaole

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

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

@liaofangyuan
Copy link

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

@haizhilin2013
Copy link
Collaborator Author

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

@jacob-lcs
Copy link

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

@liaofangyuan
Copy link

@LCS1998 你放进去试试

@jacob-lcs
Copy link

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

@liaofangyuan
Copy link

@LCS1998 期待你的答案

@NicholasBaiYa
Copy link

@LCS1998 期待你的答案

参考我的,谢谢哎

@EmiyaYang
Copy link

EmiyaYang commented Jul 30, 2019

@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];
}

@liuxiaole
Copy link

liuxiaole commented Jul 31, 2019

@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) 复杂度。

@EragonBubble
Copy link

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

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
}

@harmsworth
Copy link

/**
 * 写个方法,找出指定字符串中重复最多的字符及其长度
 */
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}

@IFmiss
Copy link

IFmiss commented Aug 13, 2019

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')

@Real102
Copy link

Real102 commented Oct 29, 2019

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');

@seho-dev
Copy link

seho-dev commented Dec 9, 2019

//
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);

@canwdev
Copy link

canwdev commented Feb 28, 2020

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')

@NAZBIN
Copy link

NAZBIN commented Jun 5, 2020

`//思路:首先对数组去重然后统计每个字符的个数最后输出最多的
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));
`

@ducky-YFH
Copy link

    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);

@xiaoqiangz
Copy link

function getMaxRepeatChar(str) {
const data = str.split('')
let obj = data.reduce((perv,cur)=> {
if (!perv[cur]) {
perv[cur] = 1
} else {
perv[cur]++
}
return perv
},{})
let list = Object.entries(obj)
list.sort((a,b)=>{
return a[1] - b[1]
})
return list[list.length - 1]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests