VOOZH about

URL: https://www.geeksforgeeks.org/dsa/string-matching-with-that-matches-with-any-in-any-of-the-two-strings/

⇱ String matching with * (that matches with any) in any of the two strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

String matching with * (that matches with any) in any of the two strings

Last Updated : 29 Nov, 2023

You are given two strings A and B. Strings also contains special character * . you can replace * with any alphabetic character. Finally, you have to tell whether it is possible to make both string same or not.

Examples:

Input : A = "gee*sforgeeks"
B = "geeksforgeeks"
Output :Yes
Input :A = "abs*"
B = "abds"
Output :No

Explanation: How we can solve above problem, Basically we three cases, 

  • Case 1: Both strings contain * at a particular position, at that time we can replace both * with any character to make the string equal at that position. 
  • Case 2: If one string has character and the other has * at that position. So, we can replace * with the same character in another string. 
  • Case 3: If both strings has a character at that position, then they must be same, otherwise we can't make them equal. 

Implementation:


Output
1

Time Complexity: O(N)

Auxiliary Space: O(1)

Two pointer Approach:

Steps:

  • If the lengths of strings A != B, return No because it's not possible to make them the same.
  • Initialize two pointers, i=0 and j= 0, pointing to the first characters of strings A and B, respectively.
  • Iterate while both pointers are within the string bounds:
    1. If the characters at pointers i and j are equal or either of them is , move both pointers to the next character.
    2. If the character at pointer i is , move pointer j until the characters at pointers i and j are equal or until pointer j reaches the end of string B.
    3. If pointer j reaches the end of string B and pointer i is not pointing to , return No because it's not possible to make them the same.
    4. If the characters at pointers i and j are not equal and pointer i is not , return No because it's not possible to make them the same.
  • If both pointers have reached the end of their respective strings, return Yes because it's possible to make them the same.
  • If either pointer i or j has not reached the end of its string, return No because it's not possible to make them the same.

Below is the implementation of above approach:


Output
No

Time Complexity: O(N), where N is the length of the input strings A and B.

Auxiliary Space: O(1)

Comment