decode ways

 1 class Solution {
 2 public:
 3    
 4     bool check(string s)
 5     {
 6         if( s.length() == 1 )
 7             return s>="1" && s <="9";
 8         if( s.length() == 2 )
 9             return s >= "10" && s <= "26" ;
10         return false;
11         
12     }
13     int decode(string s, int left, int right)
14     {
15         if( left >= s.length() ) return 1;
16         
17         if( left == right) 
18         {
19             if(s[left]>='1'&&s[left]<='9')
20                 return 1;
21             return 0;
22         }
23         
24         if( left > right )  return 1;
25         
26         int mid = (left + right )/2;
27         int l = decode( s, left, mid);
28         int r = decode( s, mid+1, right);
29         int sum = l*r;
30         
31         if( check( s.substr(mid,2)) )
32         {
33             sum += decode( s, left, mid-1)*decode( s,mid+2 ,right);
34         }
35        
36         
37         return sum;
38     }
39     int numDecodings(string s) {
40         // Start typing your C/C++ solution below
41         // DO NOT write int main() function
42         if( s == "" ) return 0;
43         
44         return  decode( s , 0, s.length()-1);
45         
46     }
47 };

 

 

posted on 2013-09-03 15:27  jumping_grass  阅读(139)  评论(0)    收藏  举报

导航