find the maximum count of consecutive time string b appears in string a
By | 8 months ago
To create a JavaScript program that finds the maximum count of consecutive occurrences of string `b` in string `a, you can iterate through
a` and check for occurrences of `b. When
b` is found, increase a counter and check if the current count is greater than the maximum found so far. If `b` is not found consecutively, reset the counter.
Here's a simple JavaScript program that implements this logic:
function maxConsecutiveCount(a, b) { let maxCount = 0; let currentCount = 0; for (let i = 0; i <= a.length - b.length; i++) { // Check if the substring from the current position matches \`b\` if (a.substring(i, i + b.length) === b) { currentCount++; i += b.length - 1; // Skip the length of \`b\` minus one since we found it // Update maxCount if the current count is greater if (currentCount > maxCount) { maxCount = currentCount; } } else { currentCount = 0; // Reset current count as consecutive sequence is broken } } return maxCount; } // Test the function const a = "popodfspo"; const b = "po"; console.log(maxConsecutiveCount(a, b)); // Output should be 2
This program defines a function `maxConsecutiveCount(a, b)` that iterates through the string `a, checking for occurrences of
b. If
b` is found, it increments `currentCount` and updates `maxCount` if necessary. When a non-consecutive occurrence is encountered, `currentCount` is reset. Finally, the function returns `maxCount, which is the maximum count of consecutive occurrences of
b` in a
.
Credits: Sijo Kuriakose - Senior Software engineer- CET-18 passout from pathenemthitta