SUBSTRINGP - Editorial

Prerequisites:- None

Problem :- Given two strings, S1 and S2, your task is to determine whether S2 is a substring of S1.

Explanation :-
Iterate through each character of the first string, S1, and check whether the second string, S2, is a substring starting from that position.

Here’s a breakdown of the core logic:
The code loops through each character of S1.
At each position in S1, it checks if the substring of S1 starting from that position matches S2.
If the substring of S1 matches S2, it means that S2 is a substring of S1. In this case, it prints “YES” and exits the loop.
If no match is found after checking all possible starting positions, it means S2 is not a substring of S1. In this case, it prints “NO”.

Solution :-
C++ Solution : -

#include <iostream>
#include <string>
using namespace std;

bool isSubstring(const string& S1, const string& S2) {
    int lenS1 = S1.length(), lenS2 = S2.length();
    for (int i = 0; i <= lenS1 - lenS2; i++) {
        bool found = true;
        for (int j = 0; j < lenS2; j++) {
            if (S1[i + j] != S2[j]) {
                found = false;
                break;
            }
        }
        if (found) return true;
    }
    return false;
}

int main() {
    int T;
    cin >> T;
    while (T--) {
        string S1, S2;
        cin >> S1 >> S2;
        cout << (isSubstring(S1, S2) ? "YES" : "NO") << endl;
    }
    return 0;
}