[leetcode]Decode Ways

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   for   ar   div   

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.

演算法思路:

思路1:遞迴。典型的遞迴演算法,不用試就知道會逾時。

 

思路2:dp。既然遞迴逾時,那就不妨試試dp了。

維護一個一維數組,dp[length]。dp[i]表示字串 i ~ length的decode ways。

初始狀態:dp[length] = 0; dp[length - 1] = dp[length - 1] = s.charAt(length - 1) == ‘0‘ ? 0 : 1;

每次讀取num = s.substring(i,i + 2)

如果大於26,則dp[i] = dp[i + 1];

如果小於等於26,則dp[i] = dp[i + 1] + dp[i + 2];

【注意】0的處理,第一遍未通過case“0”,"01","101"

 1 public class Solution { 2     public int numDecodings(String s) { 3         if(s.length() == 0) return 0; 4         int length = s.length(); 5         int[] dp = new int[length + 1]; 6         dp[length] = 1; 7         dp[length - 1] = s.charAt(length - 1) == ‘0‘ ? 0 : 1;  8         for(int i = length - 2; i >= 0; i--){ 9             if(s.charAt(i) == ‘0‘) continue;10             int tem = Integer.valueOf(s.substring(i,i + 2));11             if(tem > 26){12                 dp[i] = dp[i + 1];13             }else{14                 dp[i] = dp[i + 1] + dp[i + 2];15             }16         }17         return dp[0];18     }19 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.