假设我们有两个字符串S和T。我们必须检查S是否为T的子序列。
因此,如果输入类似于S =“ abc”,T =“ adbrcyxd”,则输出为True
为了解决这个问题,我们将遵循以下步骤-
如果s与t相同,则-
返回真
n:= s的大小,m:= t的大小
j:= 0
对于初始化i:= 0,当i <n时,更新(将i增加1),执行-
返回真
(将j增加1)
如果t [j]与s [i]相同,则-
如果j与t的大小相同,则-
返回假
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool solve(string t, string s) {
if(s == t)
return true;
int n = s.size();
int m = t.size();
int j = 0;
for(int i = 0; i < n; i++){
if(t[j] == s[i])
j++;
if(j == t.size())
return true;
}
return false;
}
};
main(){
Solution ob;
string S = "abc", T = "adbrcyxd";
cout << ob.solve(S, T);
}"abc", "adbrcyxd"
输出结果
1