2

LeetCode-091-解码方法

 2 years ago
source link: https://segmentfault.com/a/1190000040814471
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

LeetCode-091-解码方法

发布于 今天 23:31

题目描述:一条包含字母 A-Z 的消息通过以下映射进行了 编码 :

'A' -> 1
'B' -> 2
...
'Z' -> 26
要 解码 已编码的消息,所有数字必须基于上述映射的方法,反向映射回字母(可能有多种方法)。例如,"11106" 可以映射为:

"AAJF" ,将消息分组为 (1 1 10 6)
"KJF" ,将消息分组为 (11 10 6)
注意,消息不能分组为 (1 11 06) ,因为 "06" 不能映射为 "F" ,这是由于 "6" 和 "06" 在映射中并不等价。

给你一个只含数字的 非空 字符串 s ,请计算并返回 解码 方法的 总数 。

题目数据保证答案肯定是一个 32 位 的整数。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:递归 穷举
  • 首先,当snull或者是空字符串或者s是以0开头的字符串,不可能映射成功,直接返回0
  • 如果s的长度为1,直接返回1。
  • 然后是递归处理当s的长度大于1的情况,递归方法处理逻辑如下(方法的入参leftright分别为当前要匹配的字符的开始和结束位置0 < (right - left) < 3):

    • 如果left位置的数字为0即要匹配的字符是以0开头,则无法映射,直接返回;
    • 如果leftright所匹配的字符数大于26,无法映射,返回;
    • 如果rights的最后一位,则result加1,返回;
    • 如果rights的倒数第二位,且最后一位不是0,则result加1,返回;
    • 后面则根据right后的位数继续递归处理right ~ right + 1right ~ right + 2的情况。
  • 最后返回result即为解码方法的总数。
public class LeetCode_091 {

    private static int result = 0;

    /**
     * 递归 穷举:性能较差,提交会超时
     *
     * @param s
     * @return
     */
    public static int numDecodings(String s) {
        // 这些情况无法映射,直接返回0
        if (s == null || s == "" || s.equals("0") || s.startsWith("0")) {
            return 0;
        }

        if (s.length() == 1) {
            return 1;
        }

        numDecodings(s, 0, 1);
        numDecodings(s, 0, 2);
        return result;
    }



    public static void numDecodings(String s, int left, int right) {
        if (s.charAt(left) == '0') {
            return;
        }
        if (Integer.valueOf(s.substring(left, right)) > 26) {
            return;
        }
        if (s.length() - right == 0) {
            result++;
            return;
        }
        if (s.length() - right == 1 && s.charAt(s.length() - 1) != '0') {
            result++;
            return;
        }
        numDecodings(s, right, right + 1);
        if (s.length() - right > 1) {
            numDecodings(s, right, right + 2);
        }
    }

    public static void main(String[] args) {
        System.out.println(numDecodings("226"));
    }
}

【每日寄语】 与天奋斗,其乐无穷!与地奋斗,其乐无穷!与人奋斗,其乐无穷!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK