1. 程式人生 > 其它 >劃分型動態規劃 - 字串解密問題

劃分型動態規劃 - 字串解密問題

1.問題描述

有一段由A-Z組成的字母串資訊被加密成數字串
加密方式為A->1,B->2,...,Z->26
給定加密後的字串S[1...N-1],問有多少種方式解密成字母串
例子:
輸入:
-12
輸出:
-2(AB或L)

2.程式碼

//
// Created by Administrator on 2021/7/22.
//

#ifndef C__TEST01_STRINGDP_HPP
#define C__TEST01_STRINGDP_HPP

#include <vector>
/*
有一段由A-Z組成的字母串資訊被加密成數字串
加密方式為A->1,B->2,...,Z->26
給定加密後的字串S[1...N-1],問有多少種方式解密成字母串
例子:
輸入:
- 12
輸出:
- 2(AB或L)
*/

#include <vector>

class StringDP{
public:
    StringDP(vector<int> charInputN);
    int algorithmDP(vector<int> &charInput);
private:
    vector<int> charInput;
};

StringDP::StringDP(vector<int> charInputN):
charInput(charInputN){
    charInput.resize(charInputN.size());
}

int StringDP::algorithmDP(vector<int> &charInput){

    if(charInput.size() == 0){
        return 0;
    }

    vector<int> f;
    f.resize(charInput.size()+1);
    f[0] = 1; //Initilization,0 is the null
    int temp;

    for(int i = 1; i < f.size() ; ++i){
        f[i] = 0;
        if(0 < charInput[i-1] && charInput[i-1]<= 9) f[i] += f[i-1];
        temp = charInput[i-2] * 10 + charInput[i-1];
        if(10 <= temp && temp <= 26) f[i] += f[i-2];
    }
    return f[f.size() - 1];
}

#endif //C__TEST01_STRINGDP_HPP

main.cpp測試

#include <iostream>
using namespace std;
#include "StringDP.hpp"

int main() {
    vector<int> ss = {1,2, 3};
    StringDP sdp(ss);
    cout << sdp.algorithmDP(ss) << endl;
    return 0;
}

主要是給自己看的,所以肯定會出現很多錯誤哈哈哈哈哈