HackerRank : Week of Code 23 – Unexpected Problem

By | September 15, 2016

Marc is young lover of strings who wants your help with the following problem. Given a string, , of lowercase English alphabetic letters and an integer, , calculate the number of string ‘s such that:

  • Each consists of lowercase English alphabetic letters
  • , meaning their concatenation is commutative.

Print the number of string ‘s modulo .

Input Format

The first line contains a string denoting .
The second line contains an integer denoting .

Constraints

consists of lowercase English alphabetic letters only (i.e., to ).

 

Output Format

Print the number of string ‘s satisfying the conditions above, modulo .

Sample Input

abc
6

Sample Output

2

Explanation

Given abc, we have two possible string ‘s satisfying and :

  1. abc
  2. abcabc.

Solution : 


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

public class Solution {

public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
String str= scan.nextLine();
long m=scan.nextLong();

boolean isAllSame=false;

char isSame=str.charAt(0);
for (int i = 1; i < str.length(); i++)
{
if(str.charAt(i)!=isSame)
{
isAllSame=false;
break;
}
else
isAllSame=true;
}

if(isAllSame==true)
System.out.println(m);
else
{
int minLength= Integer.MAX_VALUE;
int len=str.length();

if(m>len)
{

for (int i = 0,j=len-1; i < len-1 || j>=0; i++,j–)
{
String str1=str.substring(0,i+1);
String str2=str.substring(j,len);

if(str1.length()>m)
break;

if(str1.equals(str2))
{
if(str1.length()<minLength)
minLength=str1.length();
break;

}
}

int div=(int) (m/minLength);
System.out.println(div);
}
else
{

int count=0;
int listCount=0;

for (int i = 0,j=len-1; i < len-1 || j>=0; i++,j–)
{
String str1=str.substring(0,i+1);
String str2=str.substring(j,len);

if(str1.length()>m)
break;

if(str1.equals(str2))
{
if(str1.length()<minLength)
minLength=str1.length();

listCount++;
}
}

System.out.println(count+listCount);
}

}
}
}