Use java and recursion!
Repeat substrings of the given String required number of times
Given a 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 = “1g2e1ks1” then the resultant string will be “geeks”.
Input: str = “2a3bd”
Output: aabbbddd
If you have any queries please comment in the comments section I will surely help you out and if you found this solution to be helpful kindly upvote.
Solution :
Code :
import java.util.Scanner;
public class HelloWorld
{
// main function
public static void main(String []args)
{
// declare variables
int i,j,a,k,p;
// declare an object of Scanner class
Scanner sc = new Scanner(System.in);
// input string
String s = sc.nextLine();
// declare an empty string for the answer
String ans = "";
// iterate through the loop
for(i=0;i<s.length();i++)
{
// check if the character is a digit
if(Character.isDigit(s.charAt(i)))
{
// declare an empty string
String temp="";
// now iterate from (i+1)th index to last index
for(j=i+1;j<s.length();j++)
{
// take all the letters to the temporary string
if(Character.isLetter(s.charAt(j)))
{
temp=temp+s.charAt(j);
}
// if the character is not a letter then break
else
{
break;
}
}
// take the numeric value of ith index
a = Character.getNumericValue(s.charAt(i));
// iterate over the temporary string
for(k=0;k<temp.length();k++)
{
// add every character to the answer string 'a' times
for(p=0;p<a;p++)
{
ans=ans+temp.charAt(k);
}
}
// make (j-1)th index as the ith index
i=j-1;
}
}
// print the result
System.out.println(ans);
}
}
Output :
Get Answers For Free
Most questions answered within 1 hours.