Find longest occurrence of same number in array

前端 未结 12 1513
一生所求
一生所求 2021-01-05 17:49

Using JavaScript, I\'m trying to find a way to find the longest occurrence of the same number (in this case, 1) in an array.

For instance, here\'s a sample array:

12条回答
  •  耶瑟儿~
    2021-01-05 17:57

    An alternative approach. I'm converting the array to a string. The regular expression has a backrefence, which ensures that only sequences of the same character are matched. Also when exec is used with the g flag, repeated executions will continue from the end of last match, and not from the beginning.

    var arr = [2,5,3,1,1,1,3,7,9,6,4,1,1,1,1,1,4,7,2,3,1,1,4,3];
    var str = arr.join('');
    var regex = /(.)\1*/g;
    var match;
    var largest = '';
    
    while (match = regex.exec(str)) {
      largest = match[0].length > largest.length ? match[0] : largest;
    }
    
    console.log(largest.length);
    

提交回复
热议问题