Repeat substrings of the given String required number of times
Last Updated :
20 Apr, 2023
Given string str, the task is to repeat every substring of the string X number of times where X is the number composed of the consecutive digits present just after the substring in the original string. For example, if str = "g1e2ks1" then the resultant string will be "geeks". Examples:
Input: str = "2a10bd3"
Output: aaaaaaaaaabdbdbd
Explanation: First digit "2" is unnecessary as there is no valid substring before it. "a" will be repeated 10 times and then "bd" will be repeated thrice.
Input: str = "g1ee1ks1for1g1e2ks1"
Output: geeksforgeeks
Approach: Find the first valid substring i.e. the substring which doesn't contain any digit then parse the integer present just after the found substring using parseInt() and then repeat the found substring the required number of times. Repeat these steps for all valid substrings and then print the resultant string. Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function that returns true if the
// passed character is a digit
bool isDigit(char ch)
{
if (ch >= '0' && ch <= '9')
return true;
return false;
}
// Function to return the next index
// of a non-digit character in the string
// starting at the index i (returns -1 if
// no such index is found)
int nextNonDigit(string str, int i)
{
// If the character at index i is a digit
// then skip to the next character
while (i < str.length() && isDigit(str[i]))
{
i++;
}
// If no such index was found
if (i >= str.length())
return -1;
return i;
}
// Function to append str the given number
// of times to the StringBuilder
void appendRepeated(string &sb, string str, int times)
{
for (int i = 0; i < times; i++)
sb.append(str);
}
// Function to return the string after
// performing the given operations
string findString(string str, int n)
{
// To build the resultant string
string sb = "";
// Index of the first non-digit
// character in the string
int startStr = nextNonDigit(str, 0);
// While there are substrings that
// do not consist of digits
while (startStr != -1)
{
// Find the ending of the substring
int endStr = startStr;
while ((endStr + 1) < n && !isDigit(str[endStr + 1]))
{
endStr++;
}
// Starting index of the number
int startNum = endStr + 1;
// If no digit appears after
// the current substring
if (startNum == -1)
break;
// Find the index at which the
// current number ends
int endNum = startNum;
while ((endNum + 1) < n && isDigit(str[endNum + 1]))
{
endNum++;
}
// Parse the number from the substring
int num = stoi(str.substr(startNum, endNum + 1));
// Repeat the current substring required number of times
appendRepeated(sb, str.substr(startStr, endStr + 1 - startStr), num);
// Find the next non-digit character index
startStr = nextNonDigit(str, endStr + 1);
}
// Return the resultant string
return sb;
}
// Driver Code
int main()
{
string str = "g1ee1ks1for1g1e2ks1";
int n = str.length();
cout << findString(str, n) << endl;
return 0;
}
// This code is contributed by
// sanjeev2552
Java
// Java implementation of the approach
class GFG {
// Function that returns true if the
// passed character is a digit
static boolean isDigit(char ch)
{
if (ch >= '0' && ch <= '9')
return true;
return false;
}
// Function to return the next index
// of a non-digit character in the string
// starting at the index i (returns -1 if
// no such index is found)
static int nextNonDigit(String str, int i)
{
// If the character at index i is a digit
// then skip to the next character
while (i < str.length()
&& isDigit(str.charAt(i))) {
i++;
}
// If no such index was found
if (i >= str.length())
return -1;
return i;
}
// Function to append str the given number
// of times to the StringBuilder
static void appendRepeated(StringBuilder sb,
String str, int times)
{
for (int i = 0; i < times; i++)
sb.append(str);
}
// Function to return the string after
// performing the given operations
static String findString(String str, int n)
{
// To build the resultant string
StringBuilder sb = new StringBuilder("");
// Index of the first non-digit
// character in the string
int startStr = nextNonDigit(str, 0);
// While there are substrings that
// do not consist of digits
while (startStr != -1) {
// Find the ending of the substring
int endStr = startStr;
while ((endStr + 1) < n
&& !isDigit(str.charAt(endStr + 1))) {
endStr++;
}
// Starting index of the number
int startNum = endStr + 1;
// If no digit appears after
// the current substring
if (startNum == -1)
break;
// Find the index at which the
// current number ends
int endNum = startNum;
while ((endNum + 1) < n
&& isDigit(str.charAt(endNum + 1))) {
endNum++;
}
// Parse the number from the substring
int num = Integer.parseInt(str.substring(startNum,
endNum + 1));
// Repeat the current substring required number of times
appendRepeated(sb, str.substring(startStr,
endStr + 1), num);
// Find the next non-digit character index
startStr = nextNonDigit(str, endStr + 1);
}
// Return the resultant string
return sb.toString();
}
// Driver code
public static void main(String[] args)
{
String str = "g1ee1ks1for1g1e2ks1";
int n = str.length();
System.out.println(findString(str, n));
}
}
Python3
# Python3 implementation of the approach
# Function that returns true if the
# passed character is a digit
def isDigit(ch):
if ch >= '0' and ch <= '9':
return True
return False
# Function to return the next index
# of a non-digit character in the string
# starting at the index i (returns -1 if
# no such index is found)
def nextNonDigit(string, i):
# If the character at index i is a digit
# then skip to the next character
while i < len(string) and isDigit(string[i]):
i += 1
# If no such index was found
if i >= len(string):
return -1
return i
# Function to append str the given number
# of times to the StringBuilder
def appendRepeated(sb, string, times):
for i in range(times):
sb.append(string)
# Function to return the string after
# performing the given operations
def findString(string, n):
# To build the resultant string
sb = list()
# Index of the first non-digit
# character in the string
startStr = nextNonDigit(string, 0)
# While there are substrings that
# do not consist of digits
while startStr != -1:
# Find the ending of the substring
endStr = startStr
while (endStr + 1 < n and not
isDigit(string[endStr + 1])):
endStr += 1
# Starting index of the number
startNum = endStr + 1
# If no digit appears
# after the current substring
if startNum == -1:
break
# Find the index at which the
# current number ends
endNum = startNum
while (endNum + 1 < n and
isDigit(string[endNum + 1])):
endNum += 1
# Parse the number from the substring
num = int(string[startNum:endNum + 1])
# Repeat the current substring
# required number of times
appendRepeated(sb, string[startStr:endStr + 1], num)
# Find the next non-digit character index
startStr = nextNonDigit(string, endStr + 1)
# Return the resultant string
sb = ''.join(sb)
return sb
# Driver code
if __name__ == "__main__":
string = "g1ee1ks1for1g1e2ks1"
n = len(string)
print(findString(string, n))
# This code is contributed by
# sanjeev2552
C#
// C# implementation of the approach
using System;
using System.Text;
class GFG{
// Function that returns true if the
// passed character is a digit
static bool isDigit(char ch)
{
if (ch >= '0' && ch <= '9')
return true;
return false;
}
// Function to return the next index
// of a non-digit character in the string
// starting at the index i (returns -1 if
// no such index is found)
static int nextNonDigit(string str, int i)
{
// If the character at index i is a digit
// then skip to the next character
while (i < str.Length && isDigit(str[i]))
{
i++;
}
// If no such index was found
if (i >= str.Length)
return -1;
return i;
}
// Function to append str the given number
// of times to the StringBuilder
static void appendRepeated(StringBuilder sb,
string str, int times)
{
for(int i = 0; i < times; i++)
sb.Append(str);
}
// Function to return the string after
// performing the given operations
static String findString(string str, int n)
{
// To build the resultant string
StringBuilder sb = new StringBuilder("");
// Index of the first non-digit
// character in the string
int startStr = nextNonDigit(str, 0);
// While there are substrings that
// do not consist of digits
while (startStr != -1)
{
// Find the ending of the substring
int endStr = startStr;
while ((endStr + 1) < n &&
!isDigit(str[endStr + 1]))
{
endStr++;
}
// Starting index of the number
int startNum = endStr + 1;
// If no digit appears after
// the current substring
if (startNum == -1)
break;
// Find the index at which the
// current number ends
int endNum = startNum;
while ((endNum + 1) < n &&
isDigit(str[endNum + 1]))
{
endNum++;
}
// Parse the number from the substring
int num = Int32. Parse(str.Substring(
startNum, endNum - startNum + 1));
// Repeat the current substring required
// number of times
appendRepeated(sb, str.Substring(
startStr, endStr - startStr + 1), num);
// Find the next non-digit character index
startStr = nextNonDigit(str, endStr + 1);
}
// Return the resultant string
return sb.ToString();
}
// Driver code
public static void Main(string[] args)
{
string str = "g1ee1ks1for1g1e2ks1";
int n = str.Length;
Console.Write(findString(str, n));
}
}
// This code is contributed by rutvik_56
JavaScript
<script>
// JavaScript implementation of the approach
// Function that returns true if the
// passed character is a digit
function isDigit(ch)
{
if (ch.charCodeAt(0) >= '0'.charCodeAt(0) &&
ch.charCodeAt(0) <= '9'.charCodeAt(0))
return true;
return false;
}
// Function to return the next index
// of a non-digit character in the string
// starting at the index i (returns -1 if
// no such index is found)
function nextNonDigit(string, i){
// If the character at index i is a digit
// then skip to the next character
while(i < string.length && isDigit(string[i]))
i += 1
// If no such index was found
if(i >= string.length)
return -1
return i
}
// Function to push str the given number
// of times to the StringBuilder
function appendRepeated(sb, string, times){
for(let i=0;i<times;i++)
sb.push(string)
}
// Function to return the string after
// performing the given operations
function findString(string, n){
// To build the resultant string
let sb = []
// Index of the first non-digit
// character in the string
let startStr = nextNonDigit(string, 0)
// While there are substrings that
// do not consist of digits
while(startStr != -1){
// Find the ending of the substring
let endStr = startStr
while (endStr + 1 < n &&
!isDigit(string[endStr + 1]))
endStr += 1
// Starting index of the number
let startNum = endStr + 1
// If no digit appears
// after the current substring
if(startNum == -1)
break
// Find the index at which the
// current number ends
let endNum = startNum
while (endNum + 1 < n &&
isDigit(string[endNum + 1]))
endNum += 1
// Parse the number from the substring
let num = parseInt(string.substring(startNum,endNum + 1));
// Repeat the current substring
// required number of times
appendRepeated(sb, string.substring(startStr,endStr + 1), num)
// Find the next non-digit character index
startStr = nextNonDigit(string, endStr + 1)
}
// Return the resultant string
sb = sb.join('')
return sb
}
// Driver Code
let str = "g1ee1ks1for1g1e2ks1";
let n = str.length;
document.write(findString(str, n));
// This code is contributed by shinjanpatra
</script>
Time Complexity: O(n2) where n is the length of the string.
Auxiliary Space: O(n)
Similar Reads
Repeat substrings of the given String required number of times | Set 2 (Recursion) Given string str, the task is to repeat every substring of the string X number of times where X is the number composed of the consecutive digits present just after the substring in the original string. For example, if str = âg1e2ks1â then the resultant string will be âgeeksâ. Examples: Input: str =
7 min read
Print all Substrings of length n possible from the given String Given a string str and an integer N, the task is to print all possible sub-strings of length N. Examples: Input: str = âgeeksforgeeksâ, N = 3Output: gee eek eks ksf sfo for org rge gee eek eksExplanations: All possible sub-strings of length 3 are âgeeâ, âeekâ, âeksâ, âksfâ, âsfoâ, âforâ, âorgâ, ârge
8 min read
Get K-th letter of the decoded string formed by repeating substrings Given a string S containing letter and digit and an integer K where, 2\leq S.length() \leq 100 and 1\leq K \leq 10^{9} . The task is to return the K-th letter of the new string S'.The new string S' is formed from old string S by following steps: 1. If the character read is a letter, that letter is a
6 min read
Convert to a string that is repetition of a substring of k length Given a string, find if it is possible to convert it to a string that is the repetition of a substring with k characters. To convert, we can replace one substring of length k starting at index i (zero-based indexing) such that i is divisible by K, with k characters. Examples: Input: str = "bdac", k
7 min read
Find number of contiguous Substrings with repeated patterns Given a string str consisting of digits, the task is to find the number of contiguous substrings such that the substring can be rearranged into a repetition of some string twice. Examples: Input: str="15512212"Output: 6Explanation: Possible 6 substrings are : "1551" can be rearranged to "1515""15512
8 min read
Operations required to make the string empty Given a string str, the task is to make the string empty with the given operation. In a single operation, you can pick some characters of the string (each of the picked characters should have the same frequency) and remove them from the string. Print the total operations required to make the string
5 min read
Minimum Repetitions of s1 such that s2 is a substring of it Given two strings s1 and s2, the task is to find the minimum number of times s1 has to be repeated such that s2 is a substring of it. If no such solution exists, print -1.Examples: Input: s1 = "abcd", s2 = "cdabcdab"Output: 3 Explanation: After repeating s1 three times, s1 will become âabcdabcdabcdâ
15+ min read
Find if a given string can be represented from a substring by iterating the substring ânâ times Given a string 'str', check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. Examples: Input: str = "abcabcabc" Output: true The given string is 3 times repetition of "abc" Input: str = "abadabad" Output: true The given string is 2 times r
15+ min read
Minimum rotations required to get the same string Given a string, we need to find the minimum number of rotations required to get the same string. Examples: Input : s = "geeks" Output : 5 Input : s = "aaaa" Output : 1 The idea is based on below post.A Program to check if strings are rotations of each other or not Step 1 : Initialize result = 0 (Her
11 min read
Find the number of ways to form a string of length N that can be rearranged to include S as a substring. Given an integer N and string S of size M, the task is to find the number of ways of forming string of length N such that it is possible to rearrange the string to have S as substring. Print the answer modulo 109 + 7. Note: All characters of string S are distinct. Examples: Input: N = 3, S = "abc"Ou
8 min read