The input words are processed sequentially, in the order they are given. The next word is appended to the current line if the total length of the words in that line, including the new one, does not exceed . Otherwise, the current line is terminated, and the word is printed on a new line.
Algorithm implementation
Read the input words into an array .
char s[100];Read the input data.
scanf("%d %d", &n, &k);The variable stores the current length of the output string.
ptr = 0;Read the words sequentially.
while (n--)
{Read the current word and find its length .
scanf("%s", s);
len = strlen(s);If ptr + len \le k, then the word can be printed on the current line. The length of the output string will not exceed characters.
if (ptr + len <= k)
{
ptr += len;
printf("%s ", s);
}Otherwise, the word should be printed on a new line. Set the value of for the new line to .
else
{
ptr = len;
printf("\n%s ", s);
}
}Algorithm implementation – string
Read the input data.
cin >> n >> k;The variable stores the current length of the output string.
ptr = 0;Read the words sequentially.
while (n--)
{Read the current word and find its length .
cin >> s;
len = s.size();If ptr + len \le k, then the word can be printed on the current line. The length of the output string will not exceed characters.
if (ptr + len <= k)
{
ptr += len;
cout << s << " ";
}Otherwise, the word should be printed on a new line. Set the value of for the new line to .
else
{
ptr = len;
cout << endl << s << " ";
}
}Python implementation
Read the input data.
n, k = map(int, input().split())
s = input().split()The variable stores the current length of the output string.
ptr = 0Iterate through the words in the list .
for w in s:Find the length of the word .
lw = len(w)If ptr + lw \le k, then the word can be printed on the current line. The length of the output string will not exceed characters.
if ptr + lw <= k:
ptr += lw
print(w, end=" ")Otherwise, the word should be printed on a new line. Set the value of for the new line to .
else:
ptr = lw
print()
print(w, end=" ")