Saturday, June 25, 2022

[Google][LintCode] Add Bold Tag in String

Problem: Given a string s and a list of strings dict, you need to add a closed pair of bold tag and to wrap the substrings in s that exist in dict. If two such substrings overlap, you need to wrap them together by only one pair of closed bold tag. Also, if two substrings wrapped by bold tags are consecutive, you need to combine them.

Example:

Input: s = "abcxyz123", target = ["abc", "123"]
Output: "<b>abc</b>xyz<b>123</b>
Input: s = "aaabbcc", target = ["abc", "123"]
Output: "<b>aaabbc</b>c


Approach: Here we will take a marking boolean array which will tell us whether the current character should be mark bold or not. You can look at the implementation to understand the solution which very much straight forward.


Implementation in C#:

        public static string AddBoldTag(string s, string[] dict) 

{

            int length = s?.Length ?? 0;

            if (length == 0)

            {

                return null;

            }

            bool[] bold = new bool[length];

            int currEnd = 0;

            for (int i = 0; i < length; ++i)

            {

                foreach(string word in dict)

                {

                    if (StartsWith(s, i, word))

                    {

                        currEnd = Math.Max(currEnd, i + word.Length);

                    }

                }

                bold[i] = i < currEnd;

            }

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < length; ++i)

            {

                if (bold[i] && (i == 0 || !bold[i - 1]))

                {

                    sb.Append("<b>");

                }

                sb.Append(s[i]);

                if (bold[i] && (i == length - 1 || !bold[i + 1]))

                {

                    sb.Append("</b>");

                }

            }

            return sb.ToString();

        }

private static bool StartsWith(string s, int index, string word)

        {

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

            {

                if (index + i >= s.Length)

                {

                    return false;

                }

                if (s[index + i] != word[i])

                {

                    return false;

                }

            }

            return true;

        }


Complexity: O(n * w * lw) where n is the length of s, w is the number of strings in dict and lw is the length of the largest string in dict.

No comments:

Post a Comment