fork download
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. bool isSubsequence(string s, string t) {
  6. int n = s.size(), m = t.size();
  7. int i = 0, j = 0;
  8.  
  9. // 双指针法,遍历字符串 s 和 t
  10. while (i < n && j < m) {
  11. // 如果字符匹配
  12. if (s[i] == t[j]) {
  13. j++; // 移动 t 的指针
  14. }
  15. i++; // 始终移动 s 的指针
  16. }
  17.  
  18. // 如果 j 遍历完 t,表示 t 是 s 的子序列
  19. return j == m;
  20. }
  21.  
  22. int main() {
  23. int T; // 测试用例数
  24. cin >> T;
  25.  
  26. while (T--) {
  27. int n, m;
  28. string s, t;
  29.  
  30. cin >> n >> m; // 输入字符串的长度
  31. cin >> s >> t; // 输入字符串 s 和 t
  32.  
  33. // 判断 t 是否为 s 的子序列
  34. if (isSubsequence(s, t)) {
  35. cout << "YES" << endl;
  36. } else {
  37. cout << "NO" << endl;
  38. }
  39. }
  40.  
  41. return 0;
  42. }
  43.  
Success #stdin #stdout 0s 5308KB
stdin
2
4 2
acdc
ad
4 2
accd
ad
stdout
YES
YES