Table of Contents
method 1
algorithm
Example
Output
Method 2
Home Backend Development C++ Checks whether substring S1 occurs after any occurrence of substring S2 in the given sentence

Checks whether substring S1 occurs after any occurrence of substring S2 in the given sentence

Aug 26, 2023 am 11:13 AM
examine given sentence substrings Appear

Checks whether substring S1 occurs after any occurrence of substring S2 in the given sentence

In this problem, we need to check if substring S1 occurs after any occurrence of substring S2 in a given string S. We can solve this problem by comparing the starting index of S1 and S2 in the string S. p>

Problem Statement - We are given three substrings named S, S1 and S2. String S always contains S1 as a substring. We need to check whether substring S1 appears after substring S2 in a given string S.

Example

Enter – S = "abxtutorialspointwelcomepoint", S1 = "Welcome", S2 = "point";

Output – Yes

Explanation – In string S, the “point” substring appears 2 times. One before "welcome" and the other after "welcome". So, we can say that string S1 occurs after any occurrence of string S2

Input– S = "abcdefgh", S1 = "abcd", S2 = "gh";

Output – No

ExplanationS1 is located at the beginning of string S. Therefore, S1 will not appear after substring S2.

Input– S = “abce”, S1 = “bc”, S2 = “xy”;

Output – No

Explanation – Since string S2 does not exist in string S, print No.

method 1

In this approach, we will find all starting indices of S2 substrings and store them in a collection. After that, we will get the starting index of S1. We compare each starting index of S2 with the starting index of S1 and if we find any value in the set is less than the starting index of S2, then we can say that substring S1 occurs after any occurrence of substring S2 .

algorithm

  • Define the collection that stores the starting index of substring S2.

  • Use the find() method to find the first starting index of the S2 substring.

  • Use a while loop to get all the starting indices of substring S2, and use the insert() method to store them into a collection.

  • Traverse the setting values. Returns true if any value is less than the starting index of substring S1 in the given string S.

  • Finally returns false.

Example

#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
bool isS1AfterS2(string& S, string& S1, string& S2) {
   // set to store indices of S2 in S
   unordered_set<int> indices;
   // Find all occurrences of S2 in S, and store them in set
   size_t found = S.find(S2);
   while (found != string::npos) {
      indices.insert(found);
      found = S.find(S2, found + 1);
   }
   // Compare starting indices of S1 with S2
   for (const int& index : indices) {
      if (index < S.find(S1)) {
          return true;  // S2 appears before S1
      }
   }
   return false;  // S1 appears before or at the same position as S2
}
int main(){
   string S = "abxtutorialspointwelcomepoint";
   string S1 = "welcome", S2 = "point";
   if(isS1AfterS2(S, S1, S2)) {
          cout << "Yes, string S1 appears after string S2.";
   } else { 
      cout << "No, string S1 does not appear after string S2.";
   }
   return 0;
}
Copy after login

Output

Yes, string S1 appears after string S2.
Copy after login
Copy after login

Time complexity - O(N*K), because we need to find the starting index of string S2.

Space complexity - O(N), since we store the starting index of string S2.

Method 2

In this method, we will iterate over the string. Returns true if we find that S2 occurs before S1, because string S always contains string S1.

algorithm

  • Define len, n1 and n2 variables to store the length of the variable.

  • Start traversing the string.

  • Define the 'temp string and initialize it with a substring of length n2 starting at the i-th index.

  • If temp == S2, return true.

  • Get a substring of length n1 starting from the i-th index. If temp == s1, returns false.

  • Finally returns true.

Example

#include <bits/stdc++.h>
using namespace std;
bool isS1AfterS2(string &S, string &S1, string &S2){
   // store the length of the strings
   int n1 = S1.size(), n2 = S2.size();
   // Traverse the string S from left to right
   for (int i = 0; i <= S.size() - n2; i++){
      // temporary string to store substring
      string temp;
      // get the substring
      temp = S.substr(i, n2);
      // if we find the string S2, return true as s1 always present in s.
      if (temp == S2){
          return true;
      }
      temp = S.substr(i, n1);
      // If we find s1 before s2, return false
      if (temp == S1){
          return false;
      }
   }
   return true;
}
int main(){
   string S = "abxtutorialspointwelcome";
   string S1 = "welcome", S2 = "point";
   if(isS1AfterS2(S, S1, S2)) {
      cout << "Yes, string S1 appears after string S2.";
   } else { 
      cout << "No, string S1 does not appear after string S2.";
   }
   return 0;
}
Copy after login

Output

Yes, string S1 appears after string S2.
Copy after login
Copy after login

Time complexity – O(N*min(n1, n2)), because we find substrings of length n1 and n2.

Space complexity - O(min(n1, n2), since we store substrings.

In the first method, we use a collection to store the starting index of S2, which requires more space than the code of the second method. The code of the second method is more readable than the first method. Alternatively, programmers can try to solve the problem of checking whether substring S2 appears after S1 appears.

The above is the detailed content of Checks whether substring S1 occurs after any occurrence of substring S2 in the given sentence. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Spellcheck not working in Teams [Fixed] Spellcheck not working in Teams [Fixed] Mar 06, 2024 am 09:10 AM

We've started noticing that sometimes spellcheck stops working for Teams. Spell check is an essential tool for effective communication, and any attack on it can cause considerable disruption to workflow. In this article, we'll explore common reasons why spell check might not be working as expected, and how to restore it to its previous state. So, if spell check is not working in Teams, follow the solutions mentioned in this article. Why doesn't Microsoft spell check work? There may be several reasons why Microsoft spell check is not working properly. These reasons include incompatible language settings, disabled spell check function, damaged MSTeam or MSOffice installation, etc. Also, outdated MSTeams and MSOf

How to check if application is open in Python? How to check if application is open in Python? Aug 26, 2023 pm 06:49 PM

The program being executed is called a process. A process can be an application running on the current operating system or an application related to the operating system. If an application is tied to the operating system, it first creates a process to execute itself. Other applications rely on operating system services for execution. Most applications are operating system services and background applications that maintain the operating system, software, and hardware. In python we have different methods to check if application is open or not. Let’s learn about them in detail one by one. Using the psutil.process_iter() function psutil is a module in Python that provides users with an interface to retrieve information about running processes and system utilization.

How to check if an object is iterable in Python? How to check if an object is iterable in Python? Aug 25, 2023 pm 10:05 PM

An iterable object is an object whose all elements can be iterated over using a loop or iterable function. Lists, strings, dictionaries, tuples, etc. are all called iterable objects. In Python language, there are various ways to check whether an object is iterable. Let’s take a look one by one. Using Loops In Python, we have two looping techniques, one is using "for" loop and the other is using "while" loop. Using either of these two loops, we can check if a given object is iterable. Example In this example, we will try to iterate an object using "for" loop and check if it is iterated or not. Below is the code. l=["apple",22,"orang

How to check SSD health status in Windows 11? How to check SSD health status on Win11 How to check SSD health status in Windows 11? How to check SSD health status on Win11 Feb 14, 2024 pm 08:21 PM

How to check SSD health status in Windows 11? For their fast read, write, and access speeds, SSDs are quickly replacing HDDs, but even though they are more reliable, you still need to check the health of your SSDs in Windows 11. How to operate it? In this tutorial, the editor will share with you the method. Method 1: Use WMIC1, use the key combination Win+R, type wmic, and then press or click OK. Enter2. Now, type or paste the following command to check the SSD health status: diskdrivegetstatus If you receive the "Status: OK" message, your SSD drive is operating normally.

Java program used to check if TPP students are eligible for interviews Java program used to check if TPP students are eligible for interviews Sep 06, 2023 pm 10:33 PM

Please consider the table below to know the eligibility criteria of different companies - The Chinese translation of CGPA is: GPA greater than or equal to 8 Eligible companies Google, Microsoft, Amazon, Dell, Intel, Wipro greater than or equal to 7 Tutorial points, accenture, Infosys , Emicon, Rellins greater than or equal to 6rtCamp, Cybertech, Skybags, Killer, Raymond greater than or equal to 5Patronics, Shoes, NoBrokers Let us enter the java program to check the eligibility of tpp students for interview. Method 1: Using ifelseif condition Normally when we have to check multiple conditions we use

How to check if a string starts with a specific character in Golang? How to check if a string starts with a specific character in Golang? Mar 12, 2024 pm 09:42 PM

How to check if a string starts with a specific character in Golang? When programming in Golang, you often encounter situations where you need to check whether a string begins with a specific character. To meet this requirement, we can use the functions provided by the strings package in Golang to achieve this. Next, we will introduce in detail how to use Golang to check whether a string starts with a specific character, with specific code examples. In Golang, we can use HasPrefix from the strings package

How to check if ArrayList contains a certain element in Java? How to check if ArrayList contains a certain element in Java? Sep 03, 2023 pm 04:09 PM

You can use the contains() method of the List interface to check whether an object exists in the list. contains() method booleancontains(Objecto) Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null?e==null:o.equals(e)). Parameter c - the element whose presence in this list is to be tested. Return Value Returns true if this list contains the specified element. Throws ClassCastException - if the specified element's type is incompatible with this list (optional). NullP

How to use PHP-CS-Fixer for code style checking in PHP How to use PHP-CS-Fixer for code style checking in PHP Jun 27, 2023 pm 01:27 PM

During the development process, good coding style is an important factor in improving code quality and readability. As one of the most widely used programming languages ​​in the market today, PHP's code style inspection is also particularly important. Here, we will introduce a PHP code style checking tool-PHP-CS-Fixer, and explain in detail how to perform code style checking on it. First, we need to understand what PHP-CS-Fixer is. PHP-CS-Fixer is a PHP tool created by the Symfony framework

See all articles