Open In App

Reverse the string whenever digit is encountered

Last Updated : 19 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string s of length N, the task is to traverse the string and reverse the substring from the start to the next encountered digit. After reversing the substring, update the start index to the character immediately following the digit.

Example:

Input: s = abc123def456ghi
Output: cba123fed456ihg

Input: s = abc156ghi
Output: cba156ihg

Approach:

The key idea is to identify these substrings and reverse them individually without affecting the digits. We achieve this by iterating through the string, finding the next digit, and reversing the substring before it.

Step-by-Step Approach:

  • Initialize start and end indices to 0:
  • These mark the beginning and end of substrings to be reversed.
  • Loop through the string:
    • While end is less than the string length:
    • Find the next digit's position.
    • Reverse the substring from start to end-1

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

string reverseSubstrings(string s)
{
    int start = 0;
    int end = 0;

    // Loop through the string
    while (end < s.length()) {
        // Find the next digit
        while (end < s.length() && !isdigit(s[end])) {
            end++;
        }

        // Reverse the substring from start to end-1
        reverse(s.begin() + start, s.begin() + end);

        // Update the start index to the character
        // immediately following the digit
        start = end + 1;
        end = start;
    }

    return s;
}

int main()
{
    string s = "abc123def456ghi";
    string reversed = reverseSubstrings(s);

    cout << "Original string: " << s << endl;
    cout << "Reversed string: " << reversed << endl;

    return 0;
}
Java
public class ReverseSubstrings {

    public static String reverseSubstrings(String s)
    {
        StringBuilder sb = new StringBuilder(s);
        int start = 0;
        int end = 0;

        // Loop through the string
        while (end < sb.length()) {
            // Find the next digit
            while (end < sb.length()
                   && !Character.isDigit(sb.charAt(end))) {
                end++;
            }

            // Reverse the substring from start to end-1
            sb.replace(
                start, end,
                new StringBuilder(sb.substring(start, end))
                    .reverse()
                    .toString());

            // Update the start index to the character
            // immediately following the digit
            start = end + 1;
            end = start;
        }

        return sb.toString();
    }

    public static void main(String[] args)
    {
        String s = "abc123def456ghi";
        String reversed = reverseSubstrings(s);

        System.out.println("Original string: " + s);
        System.out.println("Reversed string: " + reversed);
    }
}

// This code is contributed by shivamgupta0987654321
Python
def reverse_substrings(s):
    start = 0
    end = 0
    length = len(s)

    # Loop through the string
    while end < length:
        # Find the next digit
        while end < length and not s[end].isdigit():
            end += 1

        # Reverse the substring from start to end-1
        s = s[:start] + s[start:end][::-1] + s[end:]

        # Update the start index to the character
        # immediately following the digit
        start = end + 1
        end = start

    return s


def main():
    s = "abc123def456ghi"
    reversed_s = reverse_substrings(s)

    print("Original string:", s)
    print("Reversed string:", reversed_s)


if __name__ == "__main__":
    main()
# This code is contributed by Ayush Mishra
JavaScript
function reverseSubstrings(s) {
    let sb = s.split('');
    let start = 0;
    let end = 0;

    // Loop through the string
    while (end < sb.length) {
        // Find the next digit
        while (end < sb.length && isNaN(parseInt(sb[end]))) {
            end++;
        }

        // Reverse the substring from start to end-1
        sb.splice(
            start, end - start,
            sb.slice(start, end).reverse().join(''));

        // Update the start index to the character
        // immediately following the digit
        start = end + 1;
        end = start;
    }

    return sb.join('');
}

function main() {
    let s = "abc123def456ghi";
    let reversed = reverseSubstrings(s);

    console.log("Original string: " + s);
    console.log("Reversed string: " + reversed);
}

// Call the main function
main();

Output
Original string: abc123def456ghi
Reversed string: cba123fed456ihg

Time complexity: O(n) where n is the length of the input string.
Auxiliary space: O(n) where n is the length of the input string.


Article Tags :
Practice Tags :

Similar Reads