LeetCode - Decode Ways

Decode Ways

2013.12.27 02:32

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.

Solution1:

  This is a simple practice for dynamic programming.

  Time complexity is O(n), space complexity is O(n), where n is the length of the string.

Accepted code:

 1 // 1AC, very nice~

 2 class Solution {

 3 public:

 4     int numDecodings(string s) {

 5         // IMPORTANT: Please reset any member data you declared, as

 6         // the same Solution instance will be reused for each test case.

 7         int *a;

 8         int i, n;

 9         

10         n = s.length();

11         if(n <= 0){

12             return 0;

13         }

14         a = new int[n + 1];

15         

16         a[0] = 1;

17         if(s[n - 1] == '0'){

18             a[1] = 0;

19         }else{

20             a[1] = 1;

21         }

22         for(i = n - 2; i >= 0; --i){

23             if(s[i] == '0'){

24                 a[n - i] = 0;

25             }else{

26                 a[n - i] = a[n - i - 1];

27                 if((s[i] - '0') * 10 + (s[i + 1] - '0') <= 26){

28                     a[n - i] += a[n - i - 2];

29                 }

30             }

31         }

32         

33         n = a[n];

34         delete[] a;

35         return n;

36     }

37 };

Solution2:

  It seems an extra array is completely unnecesssary for this problem, as the recurrence relation only involves the last two states.

  Some minor changes in code will reduce space complexity to O(1). Time complexity is still O(n).

Accepted code:

 1 // 1WA, 1AC, make sure you write good code.

 2 class Solution {

 3 public:

 4     int numDecodings(string s) {

 5         // IMPORTANT: Please reset any member data you declared, as

 6         // the same Solution instance will be reused for each test case.

 7         int a1, a2, a3;

 8         int i, n;

 9         

10         n = s.length();

11         if(n <= 0){

12             return 0;

13         }

14         

15         a1 = 1;

16         if(s[n - 1] == '0'){

17             a2 = 0;

18         }else{

19             a2 = 1;

20         }

21         for(i = n - 2; i >= 0; --i){

22             if(s[i] == '0'){

23                 a3 = 0;

24             }else{

25                 a3 = a2;

26                 if((s[i] - '0') * 10 + (s[i + 1] - '0') <= 26){

27                     a3 += a1;

28                 }

29             }

30             a1 = a2;

31             a2 = a3;

32         }

33         

34         // 1WA here, 'return a2', not 'return a3'

35         return a2;

36     }

37 };

 

你可能感兴趣的:(LeetCode)