Given a string s and a string t, check if s is subsequence of t.
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).
Follow up:
If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.
Example 1:
Input: s = "abc", t = "ahbgdc" Output: trueExample 2:
Input: s = "axc", t = "ahbgdc" Output: false
Constraints:
0 <= s.length <= 100
0 <= t.length <= 10^4
- Both strings consists only of lowercase characters.
判断子序列。题目即是题意。这个题有一个followup,问如果S有很多,怎么处理。我这里给出动态规划的解法。
首先是常规解法,双指针,一个扫描S,一个扫描T。如果碰到同样的字母则两个指针都++,否则只++T的指针。T扫描完毕之后如果S没有到末尾则return false。
时间O(m + n)
空间O(1)
Java实现
1 class Solution { 2 public boolean isSubsequence(String s, String t) { 3 // corner cases 只是s为空 4 if (s == null || s.length() == 0) { 5 return true; 6 } 7 8 // normal case 9 int i = 0; 10 int j = 0; 11 int sSize = s.length(); 12 int tSize = t.length(); 13 while (i < sSize && j < tSize) { 14 if (s.charAt(i) == t.charAt(j)) { 15 i++; 16 j++; 17 } else { 18 j++; 19 } 20 } 21 if (i == sSize) { 22 return true; 23 } else { 24 return false; 25 } 26 } 27 }
动态规划。设dp[i][j]为S以i结尾的子串是否是T以j结尾的子串的subsequence。首先corner case是当S为空的时候,dp[0][j] = true。其次开始扫描,如果匹配(s[i] == t[j]),则DP值跟之前一位的DP值相同(dp[i][j] == dp[i - 1][j - 1]);如果不匹配,则dp[i][j] = dp[i][j - 1]。
时间O(mn)
空间O(mn)
Java实现
1 class Solution { 2 public boolean isSubsequence(String s, String t) { 3 int sLen = s.length(); 4 int tLen = t.length(); 5 if (sLen > tLen) { 6 return false; 7 } 8 if (sLen == 0) { 9 return true; 10 } 11 boolean[][] dp = new boolean[sLen + 1][tLen + 1]; 12 // 初始化 13 for (int j = 0; j < tLen; j++) { 14 dp[0][j] = true; 15 } 16 // dp 17 for (int i = 1; i <= sLen; i++) { 18 for (int j = 1; j <= tLen; j++) { 19 if (s.charAt(i - 1) == t.charAt(j - 1)) { 20 dp[i][j] = dp[i - 1][j - 1]; 21 } else { 22 dp[i][j] = dp[i][j - 1]; 23 } 24 } 25 } 26 return dp[sLen][tLen]; 27 } 28 }
相关题目
524. Longest Word in Dictionary through Deleting