【Leetcode】 Distinct Subsequences

来源:互联网 发布:xp 淘宝伴侣 编辑:程序博客网 时间:2024/06/04 19:29

题目链接:https://leetcode.com/problems/distinct-subsequences/

题目:

Given a string S and a string T, count the number of distinct subsequences of T in S.

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).

Here is an example:
S = "rabbbit"T = "rabbit"

Return 3.

思路:

用二维矩阵记录两字符串匹配过程。
r数组表示当s取0~i,t取0~j时字符串时,有多少种匹配方法。

当s[i]==t[j]时:
     有两种方法,一种是将s[i]当做不等于t[j]的字符,给t[j]一个留存能继续往下匹配的机会;一种是将s[i]当做等于t[j]的字符,让这两字符作为已经匹配完的部分 ;那么r[i][j]的不同匹配方案应该是这两种不同方法不同匹配种类数之和。即r[i][j]=r[i-1][j]+r[i-1][j-1]
当s[i] != t[j]时:
     只能让s[i]继续往后移动进行匹配,所以r[i][j] 应该是r[i-1][j]

注意当j=0时,表示为t为空串时,对于任意的s,都只有一种变换能将t匹配为s。所以要将r[i][0]都初始化为1。

算法:

    public int numDistinct(String s, String t) {       if(s==null||t==null||s.length()<t.length()){return 0;}int r[][] = new int[s.length() + 1][t.length() + 1];r[0][0] = 1;for (int i = 0; i <= s.length(); i++) {r[i][0] = 1;}for (int i = 1; i <= s.length(); i++) {for (int j = 1; j <= t.length(); j++) {    if (s.charAt(i - 1) == t.charAt(j - 1)) {r[i][j] = r[i - 1][j] + r[i - 1][j - 1];}else{r[i][j]=r[i-1][j];}}}return r[s.length()][t.length()];    }


0 0
原创粉丝点击