Given an integer N and a lowercase string. The string is repeated infinitely. The task is to find the No. of occurrences of a given character x in first N letters.
Input : N = 10 str = "abcac" Output : 4 Explanation: "abcacabcac" is the substring from the infinitely repeated string. In first 10 letters 'a' occurs 4 times. Input: N = 10, str = "aba" Output : 7
1. Find the occurrences of character ‘a’ in the given string.
2. Find the No. of repetitions which are required to find the ‘a’ occurrences.
3. Multiply the single string occurrences to the No. of repetitions.
4. If given n is not the multiple of given string size then we will find the ‘a’ occurrences in the remaining substring.
Below is the implementation of above approach:
# Python3 program to find the occurrences of
# character x in the infinite repeated string
# upto length n
# Function to count the character ‘a’
def countChar(str, x):
count = 0
for i in range(len(str)):
if (str[i] == x) :
count += 1
n = 10
# atleast k repetition are required
repititions = n // len(str)
count = count * repititions
# if n is not the multiple of the
# string size check for the remaining
# repeating character.
l = n % len(str)
for i in range(l):
if (str[i] == ‘a’):
count += 1
# Driver code
str = “abcac”
# This code is contributed
# by sahishelangia
- Return maximum occurring character in an input string
- Print all the duplicates in the input string
- Remove characters from the first string which are present in the second string
- Remove duplicates from a given string
- Print reverse of a string using recursion
- Write a program to print all permutations of a given string
- Divide a string in N equal parts
- Given a string, find its first non-repeating character
- Write a program to reverse an array or string
- Reverse words in a given string
- Find the smallest window in a string containing all characters of another string
- Check whether a given string is an interleaving of two other given strings
- Lexicographic rank of a string
- An in-place algorithm for String Transformation
- Count words in a given string
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.