📜  Java ArrayList打印电话号码中所有可能的单词

📅  最后修改于: 2021-04-26 06:53:54             🧑  作者: Mango

给定手机的键盘和需要按下的键,任务是打印所有可以通过按下这些数字生成的单词。

例子:

Input: str = "12" 
Output: [ad, bd, cd, ae, be, ce, af, bf, cf]
Explanation: The characters that can be formed
by pressing 1 is a, b, c and by pressing 2 characters
d, e, f can be formed.
So all the words will be a combination where first 
character belongs to a, b, c and 2nd character belongs
to d, e, f
 
Input: str = "4"
Output: [j, k, l]
Explanation: The characters that can be formed
by pressing 4 is j, k, l

方法1在这里讨论另一种方法打印电话号码中所有可能的单词

方法2
方法:该方法与另一篇文章中的方法略有不同。假设有n个按键被按下(a1 a2 a3 ..an)。找到可以使用(a2 a3 ..an)构成的所有单词。假设3个字符可以通过之前的所有单词并插入到列表中按A1,然后为每个字符串连的字符产生。

例如:

算法:

  1. 编写一个递归函数,该函数接受按键字符串并返回可以在数组列表中形成的所有单词。
  2. 如果给定字符串的长度为0,则返回包含空字符串的Arraylist。
  3. 否则递归调用函数与除原始的字符串的第一个字符,即含有从索引1的所有字符至n-1的字符串的字符串。并存储返回的arraylist,列出并创建一个新的arraylist ans
  4. 获取原始字符串第一个字符CSet的字符集
  5. 对于列表中的每一个字贯穿了CSET循环并连接列表的字CSET盈的字符内并插入在ArrayList中。
  6. 返回数组列表ans

执行:

// Java implementation of the approach
import java.util.ArrayList;
  
public class GFG {
  
    // String array to store keypad characters
    static final String codes[]
        = { " ", "abc", "def",
            "ghi", "jkl", "mno",
            "pqr", "stu", "vwx",
            "yz" };
  
    // Function that returns an Arraylist
    // which contains all the generated words
    public static ArrayList printKeyWords(String str)
    {
  
        // If str is empty
        if (str.length() == 0) {
            ArrayList baseRes = new ArrayList<>();
            baseRes.add("");
  
            // Return an Arraylist containing
            // empty string
            return baseRes;
        }
  
        // First character of str
        char ch = str.charAt(0);
  
        // Rest of the characters of str
        String restStr = str.substring(1);
  
        ArrayList prevRes = printKeyWords(restStr);
        ArrayList Res = new ArrayList<>();
  
        String code = codes[ch - '0'];
  
        for (String val : prevRes) {
  
            for (int i = 0; i < code.length(); i++) {
                Res.add(code.charAt(i) + val);
            }
        }
        return Res;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String str = "23";
  
        // Print all the possible words
        System.out.println(printKeyWords(str));
    }
}
输出:
[dg, eg, fg, dh, eh, fh, di, ei, fi]

复杂度分析:

  • 时间复杂度: O(3 n )。
    虽然递归函数运行n次。但是arraylist的大小呈指数增长。因此,arraylist中大约有3 n个元素。因此,遍历它们将花费3 n时间。
  • 空间复杂度: O(3 n )。
    存储所有单词所需的空间为O(3 n )。因为在输出中大约有3个n字。