1. 程式人生 > 其它 >劍指Offer-第10天 動態規劃(中等)

劍指Offer-第10天 動態規劃(中等)

第一題

題目連結:https://leetcode.cn/problems/ba-shu-zi-fan-yi-cheng-zi-fu-chuan-lcof/

個人題解:動態規劃
\(f[i]=\left\{\begin{matrix} f[i-1],stol(s[-1] \in [10,25])\\ f[i-1]+f[i-2] ,stol(s[-2:-1] \in others) \end{matrix}\right.\)

程式碼:

class Solution {
public:
    int translateNum(int num) {
        string ss = to_string(num);
        int len = (int)ss.size();

        vector<int> dp(len, 0);

        dp[0] = 1;
        for(int i = 1; i < len; i++) {
            if(stoi(ss.substr(i - 1, 2)) <= 25 && ss[i - 1] != '0') {
                if(i - 2 < 0) {
                    dp[i] = dp[i - 1] + 1;
                } else {
                    dp[i] = dp[i - 1] + dp[i - 2];
                }
            } else {
                dp[i] = dp[i - 1];
            }
        }

        return dp[len - 1];
    }
};

執行截圖:

第二題

題目連結:https://leetcode.cn/problems/zui-chang-bu-han-zhong-fu-zi-fu-de-zi-zi-fu-chuan-lcof/

個人題解:雜湊表+雙指標

程式碼:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        unordered_map<int,int> hash;
        int res=0;
        for(int i=0,j=0;i<s.length();i++){
            hash[s[i]]++;
            while(hash[s[i]]>1) hash[s[j++]]--;
            res=max(res,i-j+1);
        }
        return res;
    }
};

執行截圖: