Evaluate Bracket

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


side

Given a string containing substrings that should be replaced from a list of key value pairs, we want to return a deciphered string after replacing the keys with the values.

Example:

S = (Name) loves to (action)

[[name][Jane], [action][drive]]

Ans: Bob loves to drive

We should be able to replace unmatched keys in the string with  question mark(?).

Example:

S = (nam) loves to (action)

[[name][Jane], [action][drive]]

Ans: ? loves to drive

Solution:

It should be straightforward instantly that this problem deserves dictionaries.

 public  string Evaluate(string s, IList<IList<string>> dic)   {     

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

           string result = string.Empty;

           foreach (List<string> list in dic)   {

               dict[list[0]] = list[1];

           }

 

           foreach (string k in dict.Keys)      {             

               int index = s.IndexOf("(" + k + ")");

               if (index !=-1)

                   s = s.Replace("(" + k + ")", dict[k]);              

           }

          

          //In the end we should replace unmatched keys with ?

          while(s.IndexOf("(") !=-1){

           int i = s.IndexOf("(");

           int j = s.IndexOf(")");        

         

           if (i != -1 && j != -1)    {

               string sub = s.Substring(i, j-i+1);

               s = s.Replace(sub, "?");

           }

          }

         return s;

   }

}


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:* xnnpjg

Back to Top