Find the longest series in a binary digital array

How would I find the longest series from this array of binary digits - 100011101100111110011100

In this case, the answer should be = 11111

I thought about iterating over the array and checking each digit, if there is one digit, and then adding it to a new String, if its zero re-launch creates a new line, but saves the previously created String. When done, check the length of each line to see which one is the longest. I'm sure there is a simpler solution?

+5
source share
4 answers

Your algorithm is good, but you don’t need to save all the time lines - it’s all the same.

: "bestStartPosition" "bestLength". , "", " " .

- ( ) ( "" ).

+4

, , :

count = 0
longestCount = 0
foreach digit in binaryDigitArray:
   if (digit == 1) count++
   else:
      longestCount = max(count, maxCount)
      count = 0
longestCount = max(count, maxCount)

1s, . , , , , .

+3

Java 8 O (n) ( 1 ):

int maxLength = Arrays.stream(bitStr.split("0+"))
  .mapToInt(String::length)
  .max().orElse(0);

.

, 0 .


Java 7 , O (n log n) :

java API 3 :

String bits = "100011101100111110011100";

LinkedList<String> list = new LinkedList<String>(Arrays.asList(bits.split("0+")));
Collections.sort(list);
int maxLength = list.getLast().length(); // 5 for the example given

:

  • bits.split("0+") String[] 1 ( - 0+),
  • Arrays.asList() String[] List<String>
  • LinkedList .
  • . 1
  • ( ) . LinkedList - getLast(), , ,

, , " ", , MacBook Pro 1 . String , .

EDITED

Max, Arrays.sort() , 3 :

String[] split = bits.split("0+");
Arrays.sort(split);
int maxLength = split[split.length - 1].length();
+3

php, , .

, 1:

$match = preg_split("/0+/", "100011101100111110011100", -1, PREG_SPLIT_NO_EMPTY);
echo max(array_map('strlen', $match));

:

 5
0

All Articles