Saturday, November 16, 2024
Google search engine
HomeData Modelling & AIConvert a Mobile Numeric Keypad sequence to equivalent sentence

Convert a Mobile Numeric Keypad sequence to equivalent sentence

Given a string S of size N, consisting of digits [0 – 9] and character ‘.’, the task is to print the string that can be obtained by pressing the mobile keypad in the given sequence. 

Note: ‘.’ represents a break while typing.

Below is the image to represent the characters associated with each number in the keypad.

Examples: 

Input: S = “234”
Output: ADG
Explanation:
Pressing the keys 2, 3, and 4 once gives the resultant string as “ADG”.

Input: S = “22.22”
Output: BB
Explanation:
Pressing the key 2 twice gives B, and then again pressing the key twice gives B. Therefore, the resultant string is “BB”.

Approach: The given problem can be solved by storing the mobile keypad mappings in an array and then traverse the string S and convert it into its equivalent string. Follow the steps below to solve the problem:

  • Initialize an empty string, say ans to store the required result.
  • Store the string associated to each key in the mobile keypad in an array nums[] such that nums[i] represent the set of characters on pressing the digit i.
  • Traverse the given string S using the variable i and perform the following steps:
    • If S[i] is equal to ‘.’, then increment i by 1, and continue to the next iteration.
    • Otherwise, initialize a variable cnt as 0 to store the count of the same characters.
    • Iterate until S[i] is equal to S[i + 1] and in each iteration check the following conditions:
      • If cnt is equal to 2 and S[i] is 2, 3, 4, 5, 6, or 8, then break out of the loop because keys: 2, 3, 4, 5, 6, and 8 contain the same number of characters, i.e., 3.
      • If cnt is equal to 3 and S[i] is 7 or 9, then break out of the loop because keys: 7 and 9 contain the same number of characters, i.e., 4.
      • Increment the value of cnt and i by 1.
    • If S[i] is either 7 or 9, then add the character nums[str[i]][cnt%4] to the string ans.
    • Otherwise, add the character nums[str[i]][cnt%3] to the string ans.
    • Increment the value of i by 1.
  • After completing the above steps, print the value string ans as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to convert mobile numeric
// keypad sequence into its equivalent
// string
void printSentence(string str)
{
    // Store the mobile keypad mappings
    char nums[][5]
        = { "", "", "ABC", "DEF", "GHI",
            "JKL", "MNO", "PQRS", "TUV",
            "WXYZ" };
 
    // Traverse the string str
    int i = 0;
    while (str[i] != '\0') {
 
        // If the current character is
        // '.', then continue to the
        // next iteration
        if (str[i] == '.') {
            i++;
            continue;
        }
 
        // Stores the number of
        // continuous clicks
        int count = 0;
 
        // Iterate a loop to find the
        // count of same characters
        while (str[i + 1]
               && str[i] == str[i + 1]) {
 
            // 2, 3, 4, 5, 6 and 8 keys will
            // have maximum of 3 letters
            if (count == 2
                && ((str[i] >= '2'
                     && str[i] <= '6')
                    || (str[i] == '8')))
                break;
 
            // 7 and 9 keys will have
            // maximum of 4 keys
            else if (count == 3
                     && (str[i] == '7'
                         || str[i] == '9'))
                break;
            count++;
            i++;
 
            // Handle the end condition
            if (str[i] == '\0')
                break;
        }
 
        // Check if the current pressed
        // key is 7 or 9
        if (str[i] == '7' || str[i] == '9') {
            cout << nums[str[i] - 48][count % 4];
        }
 
        // Else, the key pressed is
        // either 2, 3, 4, 5, 6 or 8
        else {
            cout << nums[str[i] - 48][count % 3];
        }
        i++;
    }
}
 
// Driver Code
int main()
{
    string str = "234";
    printSentence(str);
    return 0;
}


Java




// java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
public class GFG {
 
    // Function to convert mobile numeric
    // keypad sequence into its equivalent
    // string
    static void printSentence(String S)
    {
        // Store the mobile keypad mappings
        String nums[]
            = { "",    "",    "ABC""DEF", "GHI",
                "JKL", "MNO", "PQRS", "TUV", "WXYZ" };
 
        char str[] = S.toCharArray();
 
        // Traverse the string str
        int i = 0;
        while (i < str.length) {
 
            // If the current character is
            // '.', then continue to the
            // next iteration
            if (str[i] == '.') {
                i++;
                continue;
            }
 
            // Stores the number of
            // continuous clicks
            int count = 0;
 
            // Iterate a loop to find the
            // count of same characters
            while (i + 1 < str.length
                   && str[i] == str[i + 1]) {
 
                // 2, 3, 4, 5, 6 and 8 keys will
                // have maximum of 3 letters
                if (count == 2
                    && ((str[i] >= '2' && str[i] <= '6')
                        || (str[i] == '8')))
                    break;
 
                // 7 and 9 keys will have
                // maximum of 4 keys
                else if (count == 3
                         && (str[i] == '7'
                             || str[i] == '9'))
                    break;
                count++;
                i++;
 
                // Handle the end condition
                if (i == str.length)
                    break;
            }
 
            // Check if the current pressed
            // key is 7 or 9
            if (str[i] == '7' || str[i] == '9') {
                System.out.print(
                    nums[str[i] - 48].charAt(count % 4));
            }
 
            // Else, the key pressed is
            // either 2, 3, 4, 5, 6 or 8
            else {
                System.out.print(
                    nums[str[i] - 48].charAt(count % 3));
            }
            i++;
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        String str = "234";
        printSentence(str);
    }
}
 
// This code is contributed by Kingash.


Python3




# Python3 program for the above approach
 
# Function to convert mobile numeric
# keypad sequence into its equivalent
# string
def printSentence(str1):
     
    # Store the mobile keypad mappings
    nums = [ "", "", "ABC", "DEF", "GHI", "JKL",
             "MNO", "PQRS", "TUV", "WXYZ" ]
 
    # Traverse the string str1
    i = 0
     
    while (i < len(str1)):
         
        # If the current character is
        # '.', then continue to the
        # next iteration
        if (str1[i] == '.'):
            i += 1
            continue
 
        # Stores the number of
        # continuous clicks
        count = 0
 
        # Iterate a loop to find the
        # count of same characters
        while (i + 1 < len(str1) and str1[i + 1] and
                          str1[i] == str1[i + 1]):
 
            # 2, 3, 4, 5, 6 and 8 keys will
            # have maximum of 3 letters
            if (count == 2 and ((str1[i] >= '2' and
             str1[i] <= '6') or (str1[i] == '8'))):
                break
 
            # 7 and 9 keys will have
            # maximum of 4 keys
            elif (count == 3 and (str1[i] == '7' or
                                  str1[i] == '9')):
                break
             
            count += 1
            i += 1
 
            # Handle the end condition
            if (i < len(str)):
                break
 
        # Check if the current pressed
        # key is 7 or 9
        if (str1[i] == '7' or str1[i] == '9'):
            print(nums[ord(str1[i]) - 48][count % 4], end = "")
 
        # Else, the key pressed is
        # either 2, 3, 4, 5, 6 or 8
        else:
            print(nums[ord(str1[i]) - 48][count % 3], end = "")
             
        i += 1
 
# Driver Code
if __name__ == '__main__':
     
    str1 = "234"
    printSentence(str1)
 
# This code is contributed by bgangwar59


C#




// C# program for the above approach
using System;
public class GFG
{
 
    // Function to convert mobile numeric
    // keypad sequence into its equivalent
    // string
    static void printSentence(string S)
    {
       
        // Store the mobile keypad mappings
        string[] nums
            = { "",    "",    "ABC""DEF", "GHI",
                "JKL", "MNO", "PQRS", "TUV", "WXYZ" };
 
        char[] str = S.ToCharArray();
 
        // Traverse the string str
        int i = 0;
        while (i < str.Length) {
 
            // If the current character is
            // '.', then continue to the
            // next iteration
            if (str[i] == '.') {
                i++;
                continue;
            }
 
            // Stores the number of
            // continuous clicks
            int count = 0;
 
            // Iterate a loop to find the
            // count of same characters
            while (i + 1 < str.Length
                   && str[i] == str[i + 1]) {
 
                // 2, 3, 4, 5, 6 and 8 keys will
                // have maximum of 3 letters
                if (count == 2
                    && ((str[i] >= '2' && str[i] <= '6')
                        || (str[i] == '8')))
                    break;
 
                // 7 and 9 keys will have
                // maximum of 4 keys
                else if (count == 3
                         && (str[i] == '7'
                             || str[i] == '9'))
                    break;
                count++;
                i++;
 
                // Handle the end condition
                if (i == str.Length)
                    break;
            }
 
            // Check if the current pressed
            // key is 7 or 9
            if (str[i] == '7' || str[i] == '9') {
                Console.Write(nums[str[i] - 48][count % 4]);
            }
 
            // Else, the key pressed is
            // either 2, 3, 4, 5, 6 or 8
            else {
                Console.Write(nums[str[i] - 48][count % 3]);
            }
            i++;
        }
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
 
        string str = "234";
        printSentence(str);
    }
}
 
// This code is contributed by ukasp.


Javascript




<script>
 
// Javascript program for the above approach
 
// Function to convert mobile numeric
// keypad sequence into its equivalent
// string
function printSentence(S)
{
     
    // Store the mobile keypad mappings
    let nums = [ "", "", "ABC", "DEF", "GHI",
                 "JKL", "MNO", "PQRS", "TUV", "WXYZ"];
 
    let str = S.split("");
 
    // Traverse the string str
    let i = 0;
    while (i < str.length)
    {
         
        // If the current character is
        // '.', then continue to the
        // next iteration
        if (str[i] == '.')
        {
            i++;
            continue;
        }
 
        // Stores the number of
        // continuous clicks
        let count = 0;
 
        // Iterate a loop to find the
        // count of same characters
        while (i + 1 < str.length &&
               str[i] == str[i + 1])
        {
             
            // 2, 3, 4, 5, 6 and 8 keys will
            // have maximum of 3 letters
            if (count == 2 && ((str[i] >= '2' &&
                str[i] <= '6') || (str[i] == '8')))
                break;
 
            // 7 and 9 keys will have
            // maximum of 4 keys
            else if (count == 3 && (str[i] == '7' ||
                                    str[i] == '9'))
                break;
                 
            count++;
            i++;
 
            // Handle the end condition
            if (i == str.length)
                break;
        }
 
        // Check if the current pressed
        // key is 7 or 9
        if (str[i] == '7' || str[i] == '9')
        {
            document.write(
                nums[str[i].charCodeAt(0) - 48][count % 4]);
        }
 
        // Else, the key pressed is
        // either 2, 3, 4, 5, 6 or 8
        else
        {
            document.write(
                nums[str[i].charCodeAt(0) - 48][count % 3]);
        }
        i++;
    }
}
 
// Driver Code
let str = "234";
 
printSentence(str);
 
// This code is contributed by _saurabh_jaiswal.
 
</script>


Output: 

ADG

 

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

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments