码迷,mamicode.com
首页 > 其他好文 > 详细

Decode Ways

时间:2014-09-25 21:12:28      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:decode ways   动态规划   

A message containing letters from A-Z is being encoded to numbers using the following mapping:

‘A‘ -> 1
‘B‘ -> 2
...
‘Z‘ -> 26

Given an encoded message containing digits, determine the total number of ways to decode it.

For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

The number of ways decoding "12" is 2.

看到这个题目首先想利用:http://blog.csdn.net/huruzun/article/details/39499143 这个题类似的回溯算法解决,进行适当剪枝我觉得应该能够解决,但是就是有测试案例超时。把代码贴出来,以后慎用回溯太容易超时,一旦递归深度比较大肯定超时错误。(过程写的比较复杂)

public class Solution {
    	public int numDecodings(String s) {
		if (s == null || s.length() == 0) {
			return 0;
		}
		String string = "";
		if (s.charAt(0) != '0') {
			string += s.charAt(0);
		}
		for (int i = 1; i < s.length(); i++) {
			if (s.charAt(i) == '0' && s.charAt(i - 1) == '0') {
				continue;
			}
			if (s.charAt(i) > '0' && s.charAt(i) <= '9') {
				string += s.charAt(i);
			}
			if (s.charAt(i) == '0' && s.charAt(i - 1) >= '1'
					&& s.charAt(i - 1) <= '2') {
				string += s.charAt(i);
			}
		}
		if (string.length() == 0) {
			return 0;
		}
		List<String> ans = new ArrayList<String>();
		int times = 1;
		String str = "";
		for (int i = 0; i < string.length(); i++) {
			if (string.charAt(i) >= '0' && string.charAt(i) <= '3') {
				str += string.charAt(i);
			} else {
				if (str.length() >= 1) {
					str+= string.charAt(i);
					if (str.charAt(0) == '0') {
						str = str.substring(1);
					}
					search(str, "", "", ans);
					times *= ans.size();
					str = "";
					ans.clear();
				}

			}
		}
		search(str, "", "", ans);
		times *= ans.size();
		return times;
	}

	public void search(String s, String temp, String word, List<String> ans) {
		if (s.length() == 0) {
			if (!ans.contains(temp)) {
				ans.add(word);
			}
		} else {
			int possible = s.length() > 2 ? 2 : s.length();
			for (int i = 1; i <= possible; i++) {
				String partofString = s.substring(0, i);
				if (isvalid(partofString)) {
					String oldWord = word;
					word += Integer
							.toString((Integer.parseInt(partofString) + 'A'));
					String oldTemp = temp;
					temp += partofString;
					search(s.substring(i), temp, word, ans);
					temp = oldTemp;
					word = oldWord;
				}
			}
		}
	}

	public boolean isvalid(String s) {
		Integer res = Integer.parseInt(s);
		if (res > 0 && res <= 26) {
			return true;
		} else {
			return false;
		}
	}

}


 

后来看到别人解决这个题目其实很简单,注意字符串中出现的‘0‘,每次解码就只有两种可能,要么是两个字符一起,要么是一个单独字符。动态规划加记录方法很快能解决问题。

public class Solution {
    public int numDecodings(String s) {
        if (s.length() == 0) return 0;
        int len = s.length();
        if (len < 1) return 0;
        int[] numarray = new int[len];
        int i = len - 1;
        numarray[i] = (s.charAt(i) == '0') ? 0 : 1;
        i--;
        while (i >= 0) {
            if (s.charAt(i) == '0') numarray[i] = 0;
            else if (s.charAt(i) == '1' || (s.charAt(i) == '2' && s.charAt(i+1) <= '6'))
                if (i == len - 2) {
            		numarray[i] = numarray[i+1] + 1;
            	} else {
            		numarray[i] = numarray[i+1] + numarray[i+2];
            	}
            else
                numarray[i] = numarray[i+1];
            i--;
        }
        return numarray[0];
    }
}


 

Decode Ways

标签:decode ways   动态规划   

原文地址:http://blog.csdn.net/huruzun/article/details/39555661

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!