Skip to content
Related Articles

Related Articles

License Key Formatting

View Discussion
Improve Article
Save Article
  • Last Updated : 17 Aug, 2022
View Discussion
Improve Article
Save Article

Given a string S that consists of only alphanumeric characters and dashes. The string is separated into N + 1 groups by N dashes. Also given an integer K.

We want to reformat the string S, such that each group contains exactly K characters, except for the first group, which could be shorter than K but still must contain at least one character. Furthermore, a dash must be inserted between two groups, and you should convert all lowercase letters to uppercase.

Return the reformatted string.

Examples:

Input: S = “5F3Z-2e-9-w”, K = 4
Output: “5F3Z-2E9W”
Explanation: The string S has been split into two parts,  
each part has 4 characters. 
Note that two extra dashes are not needed and can be removed.

Input: S = “2-5g-3-J”, K = 2
Output: “2-5G-3J”
Explanation: The string s has been split into three parts,  
each part has 2 characters except the first part 
as it could be shorter as mentioned above

 

Naive Approach: To solve the problem follow the below idea:

  • We will have a Greedy approach in which we will create a temporary string with only the alphanumeric characters(but in reverse) and then add the dashes after every K step.
  • The reversal is necessary at the beginning because each group contains exactly K characters, except for the first group as mentioned in the problem.

Follow the steps to solve the problem:

  • Create an empty string temp and push only the characters (in upper-case) that are different than ‘-‘.
  • Now reverse the string obtained. Also, create a string ‘ans’ to store the final string.
  • Iterate over the string and whenever ‘K’ characters are pushed in ‘ans’ push a dash “-” into the string.
  • Return ‘ans’ as the result.

Below is the implementation to solve the problem:

C++




// C++ code for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to compute the answer
string ReFormatString(string S, int K)
{
    // Create a temporary string to store
    // the alphanumeric characters only
    string temp;
    int n = S.length();
    for (int i = 0; i < n; i++) {
        if (S[i] != '-') {
 
            temp.push_back(toupper(S[i]));
        }
    }
    int len = temp.length();
 
    // String ans is created to store
    // the final string.
    string ans;
    int val = K;
 
    // Iterate over the string from right
    // to left and start pushing
    // characters at an interval of K
    for (int i = len - 1; i >= 0; i--) {
        if (val == 0) {
            val = K;
            ans.push_back('-');
        }
        ans.push_back(temp[i]);
        val--;
    }
 
    // Reverse the final string and
    // return it.
    reverse(ans.begin(), ans.end());
    return ans;
}
 
// Driver code
int main()
{
    string s = "5F3Z-2e-9-w";
    int K = 4;
 
    // Function Call
    cout << ReFormatString(s, K);
    return 0;
}


Java




class GFG {
 
  // Function to compute the answer
  public static String ReFormatString(String S, int K)
  {
 
    // Create a temporary String to store
    // the alphanumeric characters only
    String temp = "";
    int n = S.length();
    for (int i = 0; i < n; i++) {
      if (S.charAt(i) != '-') {
        temp += (Character.toUpperCase(S.charAt(i)));
      }
    }
    int len = temp.length();
 
    // String ans is created to store
    // the final String.
    String ans = "";
    int val = K;
 
    // Iterate over the String from right
    // to left and start pushing
    // characters at an interval of K
    for (int i = len - 1; i >= 0; i--) {
      if (val == 0) {
        val = K;
        ans += '-';
      }
      ans += temp.charAt(i);
      val--;
    }
 
    // Reverse the final String and
    // return it.
    char[] charArray = ans.toCharArray();
    reverse(charArray, charArray.length);
    String res = new String(charArray);
    return res;
  }
 
 
  static void reverse(char a[], int n)
  {
    char t;
    for (int i = 0; i < n / 2; i++) {
      t = a[i];
      a[i] = a[n - i - 1];
      a[n - i - 1] = t;
    }
  }
 
  public static void main(String args[]) {
    String s = "5F3Z-2e-9-w";
    int K = 4;
 
    // Function Call
    System.out.println(ReFormatString(s, K));
 
  }
}
 
// This code is contributed by Saurabh Jaiswal


C#




using System;
 
public class GFG{
 
  // Function to compute the answer
  public static string ReFormatString(string S, int K)
  {
    // Create a temporary string to store
    // the alphanumeric characters only
    string temp="";
    int n = S.Length;
    for (int i = 0; i < n; i++) {
      if (S[i] != '-') {
        temp+=(char.ToUpper(S[i]));
      }
    }
    int len = temp.Length;
 
    // String ans is created to store
    // the final string.
    string ans="";
    int val = K;
 
    // Iterate over the string from right
    // to left and start pushing
    // characters at an interval of K
    for (int i = len - 1; i >= 0; i--) {
      if (val == 0) {
        val = K;
        ans+='-';
      }
      ans+=temp[i];
      val--;
    }
 
    // Reverse the final string and
    // return it.
    char[] charArray = ans.ToCharArray();
    Array.Reverse( charArray );
    string res = new string(charArray); 
    return res;
  }
 
  static public void Main (){
    string s = "5F3Z-2e-9-w";
    int K = 4;
 
    // Function Call
    Console.WriteLine(ReFormatString(s, K));
 
  }
}
//  This code is contributed by akashish__


Output

5F3Z-2E9W

Efficient approach: To solve the problem follow the below idea:

  • Without creating any other string we will move all the dashes to the front and remove them then we will make use of the mathematical formula to calculate the number of dashes at the right of all the alphanumeric characters.
  • Number of Dashes=(Total alphanumeric elements)/(number of elements in every group)

Formula:

Number of Dashes at any step = (Total alphanumeric elements to the right of the current index) / (number of elements in every group)

Follow the steps to solve the problem:

  • Iterate from the back of the string and move all the alphanumeric characters to the back of the string.
  • Delete all the dashes from the beginning.
  • Calculate the number of dashes(rounded-up) that would be present in the final string and append free it to the original string.
  • Iterate from the front and depending on the number of dashes that would be present up to that character, move the character by that amount in the left direction. 
  • Delete all the extra dashes that would have accumulated in the front of the string
  • Return the string after all the modifications as the answer.

Below is the implementation for the above approach:

C++




// C++ code for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to compute the answer
string ReFormatString(string S, int K)
{
    int len = S.length();
    int cnt = 0;
    int x = 0;
 
    // Move the characters to the
    // back of the string.
    for (int i = len - 1; i >= 0; i--) {
        if (S[i] == '-') {
            x++;
        }
        else {
            S[i + x] = toupper(S[i]);
        }
    }
 
    // Calculate total number of
    // alphanumeric characters so
    // as to get the number of dashes
    // in the final string.
    int slen = len - x;
    int step = slen / K;
 
    // Remove x characters from the
    // start of the string
 
    reverse(S.begin(), S.end());
    int val = x;
    while (val--) {
        S.pop_back();
    }
 
    // Push the empty spaces in
    // the string (slen+step) to get
    // the final string length
 
    int temp = step;
    while (temp--)
        S.push_back(' ');
    reverse(S.begin(), S.end());
 
    len = S.length();
 
    // Using simple mathematics
    // to push the elements
    // in the string at the correct place.
 
    int i = slen, j = step, f = 0;
    while (j < len) {
 
        // At every step calculate the
        // number of dashes that would be
        // present before the character
        step = i / K;
        if (f == 1)
            step--;
        int rem = i % K;
 
        // If the remainder is zero it
        // implies that the character is a dash.
 
        if (rem == 0 and f == 0) {
            S[j - step] = '-';
            f = 1;
            continue;
        }
        S[j - step] = S[j];
        i--;
        j++;
        f = 0;
    }
    // Remove all the dashes that would have
    // accumulated in the beginning of the string.
 
    len = S.length();
    reverse(S.begin(), S.end());
    for (int i = len - 1; i >= 0; i--) {
        if (S[i] != '-') {
            break;
        }
        if (S[i] == '-')
            S.pop_back();
    }
    reverse(S.begin(), S.end());
 
    return S;
}
 
// Driver code
int main()
{
    string s = "5F3Z-2e-9-w";
    int K = 4;
 
    // Function Call
    cout << ReFormatString(s, K);
    return 0;
}


Output

5F3Z-2E9W

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!