美文网首页
电话号码字母组合

电话号码字母组合

作者: 花钱约下 | 来源:发表于2019-02-03 16:34 被阅读0次
<?php
/**
 * 电话号码的字母组合
 *
 * User: hihone
 * Date: 2019/2/3
 * Time: 15:13
 * Description:
 * 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
 * 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
 * 输入:"23"
 * 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
 */

class Solution
{
    /**
     * @param $digits
     *
     * @return array
     */
    public function letterCombinations($digits)
    {
        if (empty($digits) || $digits == 1) return [];
        $digits = str_replace(['0', '1'], ['', ''], $digits);

        $values = [
            2 => ['a', 'b', 'c'],
            3 => ['d', 'e', 'f'],
            4 => ['g', 'h', 'i'],
            5 => ['j', 'k', 'l'],
            6 => ['m', 'n', 'o'],
            7 => ['p', 'q', 'r', 's'],
            8 => ['t', 'u', 'v'],
            9 => ['w', 'x', 'y', 'z'],
        ];
        $tmpArr = [];
        foreach (str_split($digits) as $digit) {
            if (!empty($digit) && $digit != 1) array_push($tmpArr, $values[$digit]);
        }
        $result = [];
        foreach ($tmpArr as $item) {
            $result = $this->combination($item, $result);
        }

        return $result;
    }

    /**
     * @param array $data
     * @param array $result
     *
     * @return array
     */
    private function combination(array $data, $result = [])
    {
        if (empty($result)) {
            return $data;
        }
        $i = 0;
        $_data = [];
        foreach ($data as $item) {
            foreach ($result as $key => $val) {
                $_data[] = $val . $item;
                $i++;
            }
        }

        return $_data;
    }
}

$digits = '23';
$s = new Solution();
print_r($s->letterCombinations($digits));#["mp","np","op","mq","nq","oq","mr","nr","or","ms","ns","os"]

相关文章

网友评论

      本文标题:电话号码字母组合

      本文链接:https://www.haomeiwen.com/subject/qanysqtx.html