Pattern Detection

By   Tewodros   Date Posted: Feb. 23, 2022  Hits: 772   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given two strings S1 as a pattern and S2 as a list of words that should follow the pattern in S1, return if S2 follows the pattern in S1.

Example 1

S1 = “caat”

s2 = “cat mouse dog bat”

Ans = False

Example 2

S1 = “daat”

s2 = “cat mouse mouse cat”

Ans = True

Example 3

S1 = “aba”

s2 = “mouse mouse mouse ”

Ans = False

Solution

This question resembles the problem of ISOMORPHIC strings. The only difference is that on Example 3 even if the pattern tells us ‘a’ is mouse and ‘b’ is mouse too, we should return false as this breaks the pattern. That is why we use nested ifs in this problem to handle if the value is already present in the dictionary.

 Dictionary<char, string> dict = new Dictionary<char, string>();

       List<string> list = new List<string>();

       bool ans = true;

       

       string [] words = s.Split(" ");

       list = words.ToList();

       

       if(words.Length != pattern.Length) return false;

       

       for(int i=0;i<pattern.Length; i++)

       {

           if(!dict.ContainsKey(pattern[i]))

           {

               if(!dict.ContainsValue(words[i]))

                 dict[pattern[i]] = words[i];

               else

               {

                   ans= false;

                   break;

               }

           }

           else

           {

               if(!dict[pattern[i]].Equals(words[i]))  

               {    

                   ans=  false;

                   break;

               }

                 

           }

       }

       

       return ans;

 


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* lnxevb

Back to Top