616. Add-Bold-Tag-in-String

difficulty: Medium

section pre{ background-color: #eee; border: 1px solid #ddd; padding:10px; border-radius: 5px; }

Given a string s and a list of strings dict, you need to add a closed pair of bold tag <b> and </b> 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 1:

Input: 
s = "abcxyz123"
dict = ["abc","123"]
Output:
"<b>abc</b>xyz<b>123</b>"

Example 2:

Input: 
s = "aaabbcc"
dict = ["aaa","aab","bc"]
Output:
"<b>aaabbc</b>c"

Constraints:

  • The given dict won't contain duplicates, and its length won't exceed 100.

  • All the strings in input have length in range [1, 1000].

Note: This question is the same as 758: https://leetcode.com/problems/bold-words-in-string/

Method One

class Solution {
    public String addBoldTag(String s, String[] dict) {
        // 子字符串匹配的活不用我们自己来,用 s.startsWith();
        // 注意结尾收尾。
        boolean[] isBold = new boolean[s.length()];

        for(String word : dict) {
            for(int i = 0; i < s.length(); i++ ) {
                if( s.startsWith( word ,i) ) {
                    for(int j = 0; j < word.length(); j++ ) {
                        isBold[i + j] = true;
                    }
                }
            }
        }

        StringBuilder ans = new StringBuilder();
        boolean isBTagOpen = false;
        for(int i = 0; i < s.length(); i++ ) {
            if( isBold[i] && !isBTagOpen) {
                ans.append("<b>");
                isBTagOpen = true;
            }

            if(!isBold[i] && isBTagOpen) {
                ans.append("</b>");
                isBTagOpen = false;
            }
            ans.append(s.charAt(i));
        }

        if(isBTagOpen){
            ans.append("</b>");
        }
        return ans.toString();
    }
}

Last updated

Was this helpful?