[LeetCode] Is Subsequence

来源:互联网 发布:naza飞控调参软件下载 编辑:程序博客网 时间:2024/06/06 18:56

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

早场没吃饭 写了一段傻逼的o(n**2)代码:

public class Solution {//超时代码   public boolean isSubsequence(String s, String t) { boolean[][] dp=new boolean[s.length()+1][t.length()+1]; Arrays.fill(dp[0],true); for(int i=0;i<s.length();i++){ for(int j=0;j<t.length();j++){ if(s.charAt(i)==t.charAt(j)){ dp[i+1][j+1]=dp[i][j]; }else{ dp[i+1][j+1]=dp[i+1][j]; } } } return dp[dp.length-1][dp[0].length-1]; }}

简单的ac代码:

public class Solution2 { public boolean isSubsequence(String s, String t) { if(s.length()==0) return true; for(int i=0,j=0;i<t.length();i++){ if(s.charAt(j)==t.charAt(i)){ j++; if(j==s.length()) return true; } } return false; }}