电话号码的迭代字母组合

给定一个包含 [0, 9] 数字的整数数组 arr[],我们的任务是打印这些数字可能代表的所有字母组合。我们将遵循数字到字母的映射(就像电话按钮上的那样)。注意01 不映射到任何字母。所有映射如下所示:

!Mobile-Numeric

示例:

> 输入: arr[] = [2, 3]

> 输出: ad ae af bd be bf cd ce cf

> 解释: 当我们按下 2 和 3 时,ad, ae, af, bd, … cf 是可能的单词列表。

>

> 输入: arr[] = [5]

> 输出: j k l

> 解释: 当我们按下 5 时,j, k, l 是可能的单词列表。

方法:

> 这个问题背后的核心思想是基于传统的电话键盘映射,为给定的数字序列生成所有可能的字母组合。从 2 到 9 的每个数字都对应一组字母(例如,2 映射到 ‘abc‘,3 映射到 ‘def‘,依此类推)。我们的目标是将给定数字序列对应的这些字母组合起来,形成所有可能的单词

>

> 我们可以使用带有队列迭代方法来解决这个问题。首先,用一个空字符串初始化队列。对于输入数组中的每个数字,我们通过将该数字对应的所有可能的字母追加到队列中的每个字符串来扩展它们。我们重复这个过程,直到处理完所有数字并生成了所有可能的组合队列确保我们按正确的顺序构建组合。

C++


CODEBLOCK_3c867d56

Java


“java

// Java implementation to print all possible

// letter combinations using Queue

import java.util.*;

class GfG {

// Method to get all possible words

static String[] possibleWords(int[] arr) {

// Mapping digits to corresponding letters

String[] mp

= { "", "", "abc", "def", "ghi",

"jkl", "mno", "pqrs", "tuv", "wxyz" };

// List to store the result

List result = new ArrayList();

// Queue to store intermediate combinations

Queue q = new LinkedList();

q.add("");

while (!q.isEmpty()) {

// Get the front string from the queue

String prefix = q.poll();

// Check if the current string is complete

if (prefix.length() == arr.length) {

result.add(prefix);

}

else {

// Get the corresponding digit

int digit = arr[prefix.length()];

// Skip invalid digits

if (digit 9) {

continue;

}

// Add all possible letters for this digit

for (char letter :

mp[digit].toCharArray()) {

q.add(prefix + letter);

}

}

}

return result.toArray(new String[0]);

}

static void printArr(String[] words) {

for (String word : words) {

System.out.print(word + " ");

}

System.out.println();

}

public static void main(String[] args) {

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/35190.html
点赞
0.00 平均评分 (0% 分数) - 0