Determine if a pattern matches with a string or not

Given a string and a pattern, determine if the pattern matches with the string or not. The solution should not use any regex.

For example,

Input:
string – codesleepcode
pattern – XYX

Output:
X: code
Y: sleep

Input:
string – codecodecode
pattern – XXX

Output:
X: code

We can use backtracking to solve this problem. The idea is for each character in the pattern, we maintain a map that stores sub-string mapped to it. Now if any character is not seen before, we consider all possible sub-strings and recurse to see if it leads to the solution or not. If a solution is found, we print the string mapped to each distinct character in the pattern using the map.

C++

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

#include <iostream>

#include <unordered_map>

usingnamespacestd;

// Function to determine if given pattern matches with a string or not

boolmatch(stringstr,inti,stringpat,intj,auto&map)

{

intn=str.size(),m=pat.size();

// base condition

if(n<m)

returnfalse;

// if both pattern and the string reaches end

if(i==n&&j==m)

returntrue;

// if either string or pattern reaches end

if(i==n||j==m)

returnfalse;

// consider next character from the pattern

charcurr=pat[j];

// if the character is seen before

if(map.find(curr)!=map.end())

{

strings=map[curr];

intk=s.size();

// return false if next k characters of the given string

// doesn't match with s

if(str.substr(i,k).compare(s))

returnfalse;

// recurse for remaining characters if next k characters matches

returnmatch(str,i+k,pat,j+1,map);

}

// process all remaining characters in the string if current character is