First and last appearance#4726

First and last appearance (Editorial)

Count the number of occurrences of the letter '' in the string, keeping track of the indices of its first and last appearances.

Algorithm implementation

Read the string character by character until the end (up to the '' character). The index of the current character is stored in the variable . The number of occurrences of the letter '' is counted in the variable .

cnt = 0; ind = 0;
while(scanf("%c",&ch), ch != '\n')
{

The variables and store the indices of the first and last appearances of the letter ''.

  if (ch == 'f')
  {

If the letter '' is encountered and it appears for the first time (the variable is equal to ), the current index is assigned to the variable .

    if (cnt == 0) f = ind;

The letter '' is not encountered for the first time (if cnt > 0). Assign the current index to the variable .

    if (cnt > 0) s = ind;
    cnt++;
  }
  ind++;
}

Print the result based on the number of occurrences of the letter '' in the string.

if (cnt == 1)
  printf("%d\n",f);
else 
if (cnt > 1)
   printf("%d %d\n",f,s);

Java implementation

import java.util.*;

public class Main
{  
  public static void main(String[] args)
  {
    Scanner con = new Scanner(System.in);
    String str = con.nextLine(); 
    int first = str.indexOf("f");
    int last = str.lastIndexOf("f");
    if (first != -1)
    {
      if (first == last) System.out.println(first);
      else System.out.println(first + " " + last);
    }	
  }  
}  

Python implementation

Read the input string.

s = input()

Find the indices of the first and last occurrences of the symbol ''.

first_index = s.find('f')
last_index = s.rfind('f')

Print the answer.

if first_index == -1:

The letter '' does not occur.

  pass
elif first_index == last_index:

The letter '' occurs only once.

  print(first_index)
else:

The letter '' occurs two or more times.

  print(first_index, last_index)