Indexes of spaces#8981

Indexes of spaces (Editorial)

Declare two variables:

Initialize them as a = b = -1. Next, iterate over the characters of the string . If the current character is a space (s_i = ' '):

After completing the iteration:

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 (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 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:
  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.

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)