Check if a string can be split into substrings starting with N followed by N characters

Given a string str, the task is to check if it can be split into substrings such that each substring starts with a numeric value followed by a number of characters represented by that numeric integer.

Examples:

Input: str = “4g12y6hunter”
Output: Yes
Explanation:
Substrings “4g12y” and “6hunter” satisfy the given condition

Input: str = “31ba2a”
Output: No
Explanation:
The entire string cannot be split into substrings of desired types

Approach:



    Follow the steps below to solve the problem:

    • Check for the conditions when a split is not possible:
    • If the given string does not start with a number.
    • If the integer, in the beginning of a substring, is greater than the total number of succeeding characters in the remaining substring.
    • If the above two condition are not satisfied, an answer is definitely possible. Hence find the substrings recursively.

    Below is the implementation of the above approach:

    C++

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C++ Program to implement the
    // above approach
    #include <bits/stdc++.h>
    using namespace std;
      
    // Function to check if the given
    // can be split into desired
    // substrings
    bool helper(string& s, int pos)
    {
        // Length of the string
        int len = s.size();
      
        if (pos >= len)
            return true;
      
        if (!isdigit(s[pos]))
            return false;
      
        int num = 0;
      
        // Traverse the string
        for (int i = pos; i < len; i++) {
      
            // Extract the digit
            num = num * 10 + s[pos] - '0';
      
            // Check if the extracted number
            // does not exceed the remaining
            // length
            if (i + 1 + num > len)
                return false;
      
            // Check for the remaining
            // string
            if (helper(s, i + 1 + num))
                return true;
        }
      
        // If generating desired
        // substrings is not possible
        return false;
    }
      
    // Driver Code
    int main()
    {
        string s = "123abc4db1c";
        if (helper(s, 0))
            cout << "Yes";
        else
            cout << "No";
    }

    chevron_right

    
    

    Java

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java program to implement the 
    // above approach 
    import java.util.*;
      
    class GFG{
          
    // Function to check if the given 
    // can be split into desired 
    // substrings 
    public static boolean helper(String s, int pos) 
          
        // Length of the string 
        int len = s.length(); 
          
        if (pos >= len) 
            return true
        if (!Character.isDigit(s.charAt(pos)))
            return false
          
        int num = 0
          
        // Traverse the string 
        for(int i = pos; i < len; i++)
        {
              
           // Extract the digit 
           num = num * 10 + s.charAt(pos) - '0'
             
           // Check if the extracted number 
           // does not exceed the remaining 
           // length 
           if (i + 1 + num > len) 
               return false
             
           // Check for the remaining 
           // string 
           if (helper(s, i + 1 + num)) 
               return true
        
          
        // If generating desired 
        // substrings is not possible 
        return false
      
    // Driver code
    public static void main (String[] args)
    {
        String s = "123abc4db1c"
          
        if (helper(s, 0)) 
            System.out.print("Yes");
        else
            System.out.print("No");
    }
    }
      
    // This code is contributed by divyeshrabadiya07

    chevron_right

    
    

    Python3

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    # Python3 program to implement the
    # above approach
      
    # Function to check if the given
    # can be split into desired
    # substrings
    def helper(s, pos):
          
        # Length of the string
        size = len(s)
      
        if(pos >= size):
            return True
      
        if(s[pos].isdigit() == False):
            return False
      
        num = 0
      
        # Traverse the string
        for i in range(pos, size):
              
            # Extract the digit
            num = num * 10 + ord(s[pos]) - 48
      
            # Check if the extracted number
            # does not exceed the remaining
            # length
            if (i + 1 + num > size):
                return False
      
            # Check for the remaining
            # string
            if (helper(s, i + 1 + num)):
                return True
      
        # If generating desired
        # substrings is not possible
        return False
      
    # Driver Code
    s = "123abc4db1c";
      
    if (helper(s, 0)):
        print("Yes")
    else:
        print("No")
      
    # This code is contributed by Sanjit_Prasad

    chevron_right

    
    

    C#

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C# program to implement the 
    // above approach 
    using System;
      
    class GFG{
           
    // Function to check if the given 
    // can be split into desired 
    // substrings 
    public static bool helper(String s, int pos) 
           
        // Length of the string 
        int len = s.Length; 
           
        if (pos >= len) 
            return true
        if (!char.IsDigit(s[pos]))
            return false
           
        int num = 0; 
           
        // Traverse the string 
        for(int i = pos; i < len; i++)
        {
               
           // Extract the digit 
           num = num * 10 + s[pos] - '0'
              
           // Check if the extracted number 
           // does not exceed the remaining 
           // length 
           if (i + 1 + num > len) 
               return false
              
           // Check for the remaining 
           // string 
           if (helper(s, i + 1 + num)) 
               return true
        
           
        // If generating desired 
        // substrings is not possible 
        return false
       
    // Driver code
    public static void Main(String[] args)
    {
        String s = "123abc4db1c"
           
        if (helper(s, 0)) 
            Console.Write("Yes");
        else
            Console.Write("No");
    }
    }
      
    // This code is contributed by amal kumar choubey

    chevron_right

    
    

    Output:

    Yes
    


    Time Complexity: O(N)
    Auxiliary Space: O(1)

    Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.