zoukankan      html  css  js  c++  java
  • LeetCode 392. Is Subsequence

    Given a string s and a string t, check if s is subsequence of t.

    You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).

    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).

    Example 1:
    s = "abc", t = "ahbgdc"

    Return true.

    Example 2:
    s = "axc", t = "ahbgdc"

    Return false.

    分析

    这道题我先是用动态规划和二维数组来做的,但空间不够

    class Solution {
    public:
        bool isSubsequence(string s, string t) {
             int dp[s.size()+1][t.size()+1];
             for(int i=0;i<=t.size();i++)
                 dp[0][i]=1;
             for(int i=1;i<=s.size();i++){
                 dp[i][0]=0;
                 for(int j=1;j<=t.size();j++) 
                     if(s[i-1]==t[j-1])
                        dp[i][j]=dp[i-1][j-1]==1?1:0;
                     else
                        dp[i][j]=dp[i][j-1];
             }
             if(dp[s.size()][t.size()]==1)
                 return true;
             else
                 return false;
        }
    };
    

    接着,我压缩了空间,变为一维数组,虽然ac了,并且可以继续在此基础继续做一些优化,但效果不明显。

    class Solution {
    public:
        bool isSubsequence(string s, string t) {
             int dp[t.size()+1];
             for(int i=0;i<=t.size();i++)
                 dp[i]=1;
             for(int i=1;i<=s.size();i++){
             	 int t1=dp[0];
                 dp[0]=0;
                 for(int j=1;j<=t.size();j++){
    			    int t2=dp[j];
                 	if(s[i-1]==t[j-1])
                        dp[j]=t1==1?1:0;
                    else
                        dp[j]=dp[j-1];
                    t1=t2;
    			 }  
             }
             if(dp[t.size()]==1)
                return true;
             else 
                return false;
        }
    };
    

    本着不断优化的想法,还可以不用动态规划,其实这也是最容易想到的办法,但因为最近在集中训练动态规划,所以把这个办法放到了最后

    class Solution {
    public:
        bool isSubsequence(string s, string t) {
             int index=0;
             for(int i=0;i<t.size()&&index<s.size();i++)
                 if(s[index]==t[i])
                      index++;
             if(index==s.size())
                 return true;
             else
                 return false;
            
        }
    };
    
  • 相关阅读:
    网站性能在线评估
    如何测试电梯/伞/桌子/笔?
    apk反编译查看源码
    Jmeter(四)-断言/检查点
    【转】Jmeter(三)-简单的HTTP请求(非录制)
    【转】Jmeter(二)-使用代理录制脚本
    [转]Jmeter(一)-精简测试脚本
    CentOS 安装以及配置Apache php mysql
    centOS静态ip设置
    免费DDOS攻击测试工具大合集
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/8439119.html
Copyright © 2011-2022 走看看