📜  将移动数字键盘序列转换为等效的句子

📅  最后修改于: 2021-10-27 09:00:25             🧑  作者: Mango

给定一个大小为N的字符串S ,由数字[0 – 9]和字符‘.’ 组成。 ,任务是打印可以通过按给定顺序按移动键盘获得的字符串。

注意: ‘.’代表打字时的休息。

例子:

方法:给定的问题可以通过将移动键盘映射存储在一个数组中,然后遍历字符串S并将其转换为等效的字符串。请按照以下步骤解决问题:

  • 初始化一个空字符串,比如ans来存储所需的结果。
  • 将与移动键盘中每个键关联的字符串存储在数组nums[] 中,这样nums[i]表示按下数字i 时的字符集。
  • 使用变量i遍历给定的字符串S并执行以下步骤:
    • 如果S[i]等于‘.’ ,然后将i增加 1,并继续下一次迭代。
    • 否则,将变量cnt初始化为0以存储相同字符的计数。
    • 迭代直到S[i]等于S[i + 1]并在每次迭代中检查以下条件:
      • 如果cnt等于 2 并且S[i]2、3、4、5、6或 8,则跳出循环,因为键:2、3、4、5、6 和 8 包含相同的数字字符,即 3。
      • 如果cnt等于 3 且S[i]为 7 或 9,则跳出循环,因为键:7 和 9 包含相同数量的字符,即 4。
      • cnti的值增加 1。
    • 如果S[i]是 7 或 9,则将字符nums[str[i]][cnt%4] 添加到字符串ans
    • 否则,将字符nums[str[i]][cnt%3] 添加到字符串ans
    • i的值增加 1。
  • 完成上述步骤后,打印值字符串ans作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
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 str1ing 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


输出:
ADG

时间复杂度: O(N)
辅助空间: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程