# Add Bold Tag in String

`String`, `Sweep Line`, `Interval`

**Medium**

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>"Input: 
s = "aaabbcc"
dict = ["aaa","aab","bc"]
Output:
"<b>aaabbc</b>c"
```

**Example 2:**

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

**Note:**

1. The given dict won't contain duplicates, and its length won't exceed 100.
2. All the strings in input have length in range \[1, 1000].

## Solution & Analysis

### Merge Interval + Sweep Line

先找到所匹配的dict中的词对应的intervals，再合并intervals，最后插入bold tag

Another way to think about this:

1. create a list of tuples/intervals with opening/closing positions, e.g. (open\_index, close\_index)
2. merge the list of intervals (see [https://leetcode.com/problems/merge-intervals/](/lintcode/sweep-line/add-bold-tag-in-string.md))
3. go through the merged interval list and insert the tags into the string

#### Java String indexOf()

IIRC Java's implementation of `.indexOf()` is just the [naive string matching algorithm](http://en.wikipedia.org/wiki/String_searching_algorithm), which is `O(n+m)` average and `O(n*m)` worst case.

12 ms, faster than 80.46%

```java
public class Solution {
    public class Interval{
        int start;
        int end;
        Interval(int start,int end){
            this.start = start;
            this.end = end;
        }
    }
    public String addBoldTag(String s, String[] dict) {
        List<Interval> intervals = new ArrayList<>();
        for(String str: dict) {
            int index = s.indexOf(str, 0);
            while(index != -1){
                 intervals.add(new Interval(index, index + str.length()));
                 index = s.indexOf(str, index + 1);
            }
        }
        Collections.sort(intervals,new Comparator<Interval>() {
            public int compare(Interval a,Interval b){
                return a.start - b.start;
            }
        });
        List<Interval> mergedIntervals = mergeInterval(intervals);

        int pre = 0;
        StringBuilder sb = new StringBuilder();
        for(Interval interval: mergedIntervals) {
             sb.append(s.substring(pre, interval.start));
             sb.append("<b>" + s.substring(interval.start, interval.end) + "</b>");
             pre = interval.end;
        }

        if(pre < s.length()){
            sb.append(s.substring(pre));
        }

        return sb.toString();
    }

    public List<Interval> mergeInterval(List<Interval> intervals) {
        List<Interval> mergedIntervals = new ArrayList<>();
        if(intervals == null || intervals.size() == 0) {
             return mergedIntervals;  
        } 

        mergedIntervals.add(intervals.get(0));
        for(int i = 1; i<intervals.size(); i++){
             Interval temp = intervals.get(i);
             if(temp.start > mergedIntervals.get(mergedIntervals.size() - 1).end) {
                 mergedIntervals.add(temp);
             } else {
                 int max = Math.max(mergedIntervals.get(mergedIntervals.size() - 1).end, temp.end);
                 mergedIntervals.get(mergedIntervals.size() - 1).end = max;
             }
        }
        return mergedIntervals;
    }
}
```

### Trie for String Search

<https://leetcode.com/problems/add-bold-tag-in-string/discuss/104250/Java-Trie-Solution>

33 ms, faster than 32.72%

```java
class Solution {
    String prefix = "<b>";
    String suffix = "</b>";
    public String addBoldTag(String s, String[] dict) {
        if (s == null) {
            return "";
        }
        int end = -1;
        StringBuilder sb = new StringBuilder();
        Trie trie = new Trie();
        for (String word : dict) trie.insert(word);
        for (int i = 0; i < s.length(); i++) {
            if (end >= i) {
                end = Math.max(end, trie.search(s, i));
            } else {
                end = trie.search(s, i);
                if (end > i) {
                    sb.append(prefix);
                }
            }
            if (end == i) sb.append(suffix);
            sb.append(s.charAt(i));
        }
        if (end == s.length()) sb.append(suffix);
        return sb.toString();
    }

    public static class Trie {
        TrieNode root;
        public Trie() {
            root = new TrieNode();
        }
        public void insert(String word) {
            if (word == null) return;
            TrieNode node = root;
            for (char c : word.toCharArray()) {
                if (!node.map.containsKey(c)) {
                    node.map.put(c, new TrieNode());
                }
                node = node.map.get(c);
            }
            node.end = true;
        }
        public int search(String s, int index) {
            TrieNode node = root;
            int res = -1;
            while (node != null && index < s.length()) {
                node = node.map.getOrDefault(s.charAt(index++), null);
                if (node != null && node.end == true) {
                    res = index;
                }
            }
            return res;
        }
    }

    public static class TrieNode {
        Map<Character, TrieNode> map;
        boolean end;
        public TrieNode() {
            map = new HashMap<>();
            end = false;
        }
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://aaronice.gitbook.io/lintcode/sweep-line/add-bold-tag-in-string.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
