Declare two variables:
is the index of the first space;
is the index of the last space;
Initialize them as a = b = -1. Next, iterate over the characters of the string . If the current character is a space (s_i = ' '):
If no spaces have been encountered before (a = -1), set a = i;
In any case, update b = i;
After completing the iteration:
If there are no spaces in the string (a = -1), print .
Otherwise, print the indices of the first and last spaces ( and ).
Algorithm implementation
Read the input string.
getline(cin, s);Initialize the variables and as the indices of the first and last spaces.
a = b = -1;
for (i = 0; i < s.size(); i++)If the current character s_i is a space
If no spaces have been encountered before (a = -1), set a = i;
Update b = i;
if (s[i] == ' ')
{
if (a == -1) a = i;
b = i;
}If there are no spaces in the string (a = -1), print . Otherwise, print the indices of the first and last spaces.
if (a == -1) printf("-1\n");
else printf("%d %d\n", a, b);Python implementation
Read the input string.
s = input()Initialize the variables and as the indices of the first and last spaces.
a = b = -1
for i in range(len(s)):If the current character s_i is a space
If no spaces have been encountered before (a = -1), set a = i;
Update b = i;
if s[i] == ' ':
if a == -1: a = i
b = iIf there are no spaces in the string (a = -1), print . Otherwise, print the indices of the first and last spaces.
if a == -1:
print("-1")
else:
print(a, b)Python implementation — find, rfind
Read the input string.
s = input()Find the indices of the first and last space.
The find function returns the index of the first occurrence of a substring in a string.
The rfind function returns the index of the last occurrence of a substring in a string.
Both functions return if the substring is not found.
a = s.find(' ')
b = s.rfind(' ')If there are no spaces in the string (a = -1), print . Otherwise, print the indices of the first and last spaces.
if a == -1:
print("-1")
else:
print(a, b)