Repeated String Solution in Java
Lilah has a string s of lowercase English letters that she repeated infinitely many times. Given an integer n, find and print the number of letter a in the first n letters of Lilah's infinite string.
For example, if the string s = "abcac" and n = 10, the substring we consider it "abcacabcac" the first 10 character of her infinite string. There are 4 occurrences of a in the substring.
So let's see solution of that.
import java.util.Scanner;
public class RepeatedString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number");
int number = sc.nextInt();
System.out.println("Enter String");
String str = sc.next();
int lengthOfstr = str.length();
long occurenceOfA = 0;
// Get all occurence of 'a' in given string
for(int i=0; i< lengthOfstr;i++) {
if(str.charAt(i)=='a') {
occurenceOfA++;
}
}
// Get repeated string length
long totalOccurence = occurenceOfA * ( number/lengthOfstr);
long remainingStr = number % lengthOfstr;
// Loop through remaining string and count occurence
// of 'a' character
for(int i=0; i<remainingStr; i++) {
char ch = str.charAt(i);
if(ch == 'a')
totalOccurence++;
}
System.out.println(totalOccurence);
}
}
Output :-
Enter Number
10
Enter String
aba
7
Enter Number
100000000
Enter String
a
100000000
See other solution of HackerRank's Problem
- https://uniquethrowdown.blogspot.com/2020/10/sales-by-match-hackerrank-java-solution.html
- https://uniquethrowdown.blogspot.com/2020/10/counting-valleys-hackerrank-solution-in.html
Comments
Post a Comment