HackerRank "Square Subsequences" !!!

Firt thought: an variation to LCS problem - but this one has many tricky detail.

I learnt the solution from this link:
https://github.com/wangyongliang/Algorithm/blob/master/hackerrank/Strings/Square%20Subsequences/main.cc

And here is his code with my comments..

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

long long lcs(string &a, string &b)
{
    int sizea = a.length();
    int sizeb = b.length();
    vector<vector<long long>> dp(sizea, vector<long long>(sizeb));
    
    //  We only consider prefixes with a[0] matched
    //  to avoid duplicate counting
    for(int i = 0; i < sizeb; i ++)
    {
        if(a[0] == b[i]) dp[0][i] = 1;
        if(i) dp[0][i] += dp[0][i - 1]; // we count accumulated
        dp[0][i] %= 1000000007;
    }
    
    for(int i = 1; i < sizea; i ++)
    {
        dp[i][0]  = dp[i - 1][0]; // all from dp[0][0]; part of init
        for(int j = 1; j < sizeb; j ++)
        {            
            dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; // accumulated version of LCS.
            if(a[i] != b[j]) dp[i][j] -= dp[i-1][j-1]; // TODO: need 2nd thought on why
            dp[i][j] %= 1000000007;
        }
    }
    return dp.back().back();
}

int main() 
{
    int t; cin >> t;
    string str;
    while(t--)
    {
        cin >> str;
        long long ans = 0;
        for(int i = 1; i < str.length(); i ++)
        {
            string sb = str.substr(i, str.length()- i);
            string sa = str.substr(0, i);
            ans += lcs(sb, sa);
            ans %= 1000000007;
        }
        cout << ans << endl;
    }
        
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/tonix/p/5595674.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值