Similar Problems
Similar Problems not available
Split Message Based On Limit - Leetcode Solution
Companies:
LeetCode: Split Message Based On Limit Leetcode Solution
Difficulty: Hard
Topics: string binary-search
Problem:
Given a string s and an integer limit, split s into substrings with a maximum length of limit. Return the array of the substrings.
Example:
Input: s = "leetcode", limit = 2 Output: ["le", "et", "co", "de"]
Input: s = "abc", limit = 4 Output: ["abc"]
Input: s = "abcdefg", limit = 3 Output: ["abc", "def", "g"]
Solution:
One way to solve this problem is to use a loop to iterate through the string s and split it into substrings with a maximum length of limit. We can use the substring() method to extract substrings from s. We start with index 0 and extract a substring of length limit. We then move to the next starting index, which is limit, and extract another substring of length limit. We continue this until we have processed the entire string s.
In each iteration of the loop, we add the extracted substring to an array of substrings. We can use the push() method to add a new element to the end of an array. Once we have processed the entire string s, we return the array of substrings.
Here is the code for this algorithm:
function splitMessage(s, limit) { let result = []; let start = 0; while (start < s.length) { let substring = s.substring(start, start + limit); result.push(substring); start += limit; } return result; }
Let's test this function with the example inputs:
console.log(splitMessage("leetcode", 2)); // ["le", "et", "co", "de"] console.log(splitMessage("abc", 4)); // ["abc"] console.log(splitMessage("abcdefg", 3)); // ["abc", "def", "g"]
The output is correct and matches the expected results.
Split Message Based On Limit Solution Code
1