zoukankan      html  css  js  c++  java
  • LeetCode: Decode Ways

    一开始dfs runtime exceed, 后来用dp想复杂了就看网上答案

     1 class Solution {
     2 public:
     3     int numDecodings(string s) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         int sum = 0;
     7         if (s.size() == 0) return sum;
     8         if (s.size() == 1 && s[0] >= '1' && s[0] <= '9') return 1;
     9         if (s[0] == '0') return 0;
    10         vector<int> ret(s.size());
    11         ret[0] = 1;
    12         for (int i = 1; i < s.size(); i++) {
    13             if (s.substr(i-1, 2) >= "10" && s.substr(i-1, 2) <= "26") {
    14                 if (i > 1) ret[i] += ret[i-2];
    15                 else ret[i] += 1;
    16             }
    17             if (s[i] >= '1' && s[i] <= '9') ret[i] += ret[i-1];
    18         }
    19         return ret[s.size()-1];
    20     }
    21 };

     C#

     1 public class Solution {
     2     public int NumDecodings(string s) {
     3         int sum = 0;
     4         if (s.Length == 0) return sum;
     5         if (s.Length == 1 && s[0] >= '1' && s[0] <= '9') return 1;
     6         if (s[0] == '0') return 0;
     7         int[] ans = new int[s.Length];
     8         ans[0] = 1;
     9         for (int i = 1; i < s.Length; i++) {
    10             if (string.Compare(s.Substring(i-1, 2), "10") >= 0 && string.Compare(s.Substring(i-1, 2), "26") <= 0) {
    11                 if (i > 1) ans[i] += ans[i-2];
    12                 else ans[i]++;
    13             }
    14             if (s[i] >= '1' && s[i] <= '9') ans[i] += ans[i-1];
    15         }
    16         return ans[s.Length-1];
    17     }
    18 }
    View Code
  • 相关阅读:
    easypoi添加下拉预选值
    java启动项目字符编码和配置文件的字符编码问题
    leetcode
    leetcode
    leetcode
    leetcode
    事务的隔离级别- 极客时间()
    数据库的事务
    SQL中的视图(极客时间)
    SQL中的连接(极客时间)
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/2970401.html
Copyright © 2011-2022 走看看