如何获得最长的相同字符序列,如果不止一个,它们有多少?

问题描述 投票:2回答:3

例子:

  • 11ADD = 2相等,2个序列
  • 115222 3等于,1序列
  • ABCDEF10 = 1相等,8个序列

结果应该包含

  1. 最大顺序重复字符数的长度。
  2. 与最大长度计数匹配的重复字符序列数

这是我正在尝试的,将十进制转换为十六进制,然后找到相等的seq。他们有多少人

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)
javascript arrays sequence equals
3个回答
0
投票

这里所有的功劳都归于其他答案。 https://stackoverflow.com/a/52152057/125981我只是根据一系列值来调整结果。请投票/接受那一个。

var sequences = ['11ADD', '115222', 'ABCDEF10'];

function getLongestSeqList(input) {
  return input
    .match(/(.)\1*/g)
    .sort((a, b) => b.length - a.length)
    .filter((a, i, arr) => a.length === arr[0].length)
}

function getValues(s) {
  let seq = getLongestSeqList(s);
  return {
    Count: seq.length,
    Len: seq[0].length
  };
}
sequences.forEach(function(s) {
  console.log(getValues(s));
});

2
投票

您可以使用简单的正则表达式获取相同字符的最长序列列表,按长度按降序排序,并按第一个长度(最长)过滤:

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

1
投票

    const getLongest = seq => seq.reduce(({
  longest,
  currentItem,
  currentLength,
  items
}, item) => {

  const newCurrentLength = currentItem === item ? currentLength + 1 : 1;
  if (newCurrentLength > longest) {
    // we have a new longest sequence, assign new values
    // to longest and items
    return {
      currentItem: item,
      currentLength: newCurrentLength,
      longest: newCurrentLength, 
      items: 1,
    };
  } else if (newCurrentLength === longest) {
    // we match the previously longest,
    // add the item to the sequence list
    return {
      currentItem: item,
      currentLength: longest,
      longest, 
      items: items + 1,
    };
  } else {
    // this is still a shorter sequence,
    // just update the local state
    return {
      currentItem: item,
      currentLength: newCurrentLength,
      longest,
      items
    }
  }


  return ;

}, {
  longest: 0,
  currentItem: undefined,
  currentLength: 0,
  items: 0
});

const values = ["11ADD", "115222", "ABCDEF10"];

const res = values.map(s => s.split("")).map(getLongest);

console.log(res);

请注意,使用此组织,您可以轻松地将数据添加到结果中,例如最长序列的值,启动位置等等...

© www.soinside.com 2019 - 2024. All rights reserved.