CLASSMATES-Editorial

PROBLEM LINK:

CLASSMATE NAMES | CodeChef
Author: Charan Narukulla

DIFFICULTY:

SIMPLE

PREREQUISITES:

String handling

PROBLEM:

Vamshi would like to code to get the longest common text from the initial position of every classmate’s first name.
Help Vamshi to code it.

EXPLANATION:

The best way to do this is as follows:

  • Store all the strings.
  • Iterate through each string.
  • Take the first string and iterate , update the first string common prefix.
  • Now the final answer is available in the first string itself.

SOLUTIONS:

Setter's Solution
/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;


class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
	 Scanner sc=new Scanner(System.in);
	 
	 String[] sall=new String[sc.nextInt()];
	 for(int i=0;i<sall.length;i++)
	 sall[i]=sc.next();
	 String cur=sall[0];
	 for(int j=1;j<sall.length;j++){
	       while(sall[j].indexOf(cur) != 0)
            cur = cur.substring(0, cur.length()-1);
	     
	     
	 }
	 if(cur.length()==0)
	System.out.println("null");
	else
	System.out.println(cur);
  }

}