zoukankan      html  css  js  c++  java
  • 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.

    这一题使用DR来做最简洁。 如果用burust的方法也行,但是时间复杂度很高。。。。

    n(T.length())

    m(S.length())

    [m,n] 表示在S的前m个字符里, T的前n个字符组成的字符串的出现次数。

    故:[m,n] = [m -1, n] + [m-1,n-1]a,  (a = 1 if(S.charAt(m) == T.charAt(n)).

    然后还需要判断一下test case。

     1 public class Solution {
     2     public int numDistinct(String S, String T) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         if(T.length() == 0 || S.length() == 0) return 0;
     6         
     7         int[][] map = new int[S.length()][T.length()];
     8         map[0][0] = (S.charAt(0) == T.charAt(0)) ? 1 : 0;
     9         int count = 0;
    10         for(int i = 0; i < S.length(); i ++){
    11             if(S.charAt(i) == T.charAt(0)) count ++;
    12             map[i][0] = count;
    13         }
    14         
    15         for(int i = 1; i < T.length(); i ++){
    16             for(int j = 1; j < S.length(); j ++){
    17                 map[j][i] = map[j-1][i];
    18                 if(S.charAt(j) == T.charAt(i)){
    19                     map[j][i] += map[j-1][i-1];
    20                 }
    21             }
    22         }
    23         return map[S.length()-1][T.length()-1];
    24     }
    25 }
  • 相关阅读:
    C#正则表达式(2):常用的特殊字符(元字符,限定字符)
    asp.net中路径
    C#正则表达式常用元字符
    iTextSharp插入图像
    iTextSharp中中文显示实例
    asp.net中MD5
    sql语句操作数据库之新增
    asp.net使用uploadify上传文件不能超过4mb的解决方案
    在浏览器地址栏中执行js代码
    MSSQL系统常用全局变量
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3316588.html
Copyright © 2011-2022 走看看