Given a string s and a string t, check if s is subsequence of t.this
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).code
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).orm
Example 1:
s = "abc"
, t = "ahbgdc"
遞歸
Return true
.rem
Example 2:
s = "axc"
, t = "ahbgdc"
字符串
Return false
.string
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?it
可用DP 貪心 二分查找。io
1.最簡單的作法,掃描一遍就好form
if (s == "")return true; int index = 0; for (int i = 0; i < t.size(); i++) { if (s[index] == t[i]) { index++; if (index >= s.size())return true; } } return false;
2. 暴力遞歸搜索
bool f(int a, int b) { if (sa =="" )return true; if (a > sa.size())return true;//若是大於 那麼表示前面全部的都匹配了所以true if (b > sb.size())return false;//b的index大於大小,意味着搜索完了還沒return true所以false if (sa[a] == sb[b])//若是相同 那麼直接遞歸下一個index { return f(a + 1, b + 1); } else { return f(a, b + 1);//不一樣則移動sb的index } }
3.吧暴力遞歸轉換爲DP
bool arr[10][10];//a b memset(arr, 0, 10 * 10); for (int b = 0; b < 10;b++)arr[0][b] = true;//初始化 字符串空 for (int a = sa.size(); a < 10; a++) { for (int b =0; b < 10; b++) arr[a][b] = true; // 初始化a>sa.size的狀況 } for (int a = sa.size() - 1;a>=0; a--)//遞推求解,遞推公式和遞歸公式同樣,可是循環條件是逆向,由於遞歸到底之後是倒着返回來的,因此遞推要倒着 { for (int b = sb.size() - 1;b>=0; b--) { if (sa[a] == sb[b]) { arr[a][b] = arr[a + 1][b + 1]; } else { arr[a][b] = arr[a][b + 1]; } } } cout << arr[0][0] << endl; cout << f(0, 0) << endl;