示例:
- 11ADD = 2 个相等,2 个序列
- 115222 3 个等于,1 个序列
- ABCDEF10 = 1 个相等,8 个序列
结果应包含
- 最大连续重复字符数的长度。
- 与最大长度计数匹配的重复字符序列数
这是我正在尝试的,将十进制转换为十六进制,然后找到相等的序列。他们有多少人
let n = [1, 26, 221];
let arr = [];
let hex = '';
let maxSequence = 0;
let currentCounter = 0;
let sequences = 0;
arr.forEach(element => {
hex += element.toString(16).toLocaleUpperCase();
});
let newarr = [];
const hexSplit = [...hex];
hexSplit.forEach((element, x) => {
if (hexSplit[x + 1] === hexSplit[x]) {
currentCounter++;
newarr.push(hexSplit[x])
}
if (currentCounter > maxSequence) {
maxSequence = currentCounter;
sequences += 1;
} else if (maxSequence === 0) {
maxSequence = 1;
sequences = hexSplit.length;
}
});
console.log(maxSequence, sequences)
最佳答案
您可以使用简单的正则表达式获取最长的相等字符序列的列表,按长度降序对其进行排序,并按第一个(最长的)的长度进行过滤:
function getLongestSeqList(input) {
return input
.match(/(.)\1*/g)
.sort((a,b) => b.length - a.length)
.filter((a,i,arr) => a.length === arr[0].length)
}
console.log(getLongestSeqList('11ADD')); // ["11", "DD"]
console.log(getLongestSeqList('115222')); // ["222"]
console.log(getLongestSeqList('ABCDEF10')); // ["A", "B", "C", "D", "E", "F", "1", "0"]
关于javascript - 如何获得最长的相等字符序列,如果超过一个,则有多少个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52151422/