LeetCode 616 - Add Bold Tag in String


Related: LeetCode 758 - Bold Words in String
https://leetcode.com/articles/add-bold-tag-in-a-string/
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"
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].

Approach #3 Using Boolean(Marking) Array
  • Time complexity : O(l*s*x). Three nested loops are there to fill bold array.
  • Space complexity : O(s)res and bold size grows upto O(s).
Another idea could be to merge the process of identification of the substrings in s matching with the words in dict. To do so, we make use of an array boldfor marking the positions of the substrings in s which are present in dict. A True value at bold[i] indicates that the current character is a part of the substring which is present in dict.
We identify the substrings in s which are present in dict similar to the last approach, by considering only substrings of length length_d for a dictionary word d. Whenver such a substring is found with its beginning index as i(and end index (i + length_d -1)), we mark all such positions in bold as True.
Thus, in this way, whenever a overlapping or consecutive matching substrings exist in s, a continuous sequence of True values is present in bold. Keeping this idea in mind, we traverse over the string s and keep on putting the current character in the resultant string res. At every step, we also check if the boldarray contains the beginning or end of a continuous sequence of True values. At the beginnning of such a sequence, we put an opening bold tag and then keep on putting the characters of s till we find a position corresponding to which the last sequence of continuous True values breaks(the first False value is found). We put a closing bold tag at such a position. After this, we again keep on putting the characters of s in res till we find the next True value and we keep on continuing the process in the same manner.
    public String addBoldTag(String s, String[] dict) {
        boolean[] bold = new boolean[s.length()];
        for (String d: dict) {
            for (int i = 0; i <= s.length() - d.length(); i++) {
                if (s.substring(i, i + d.length()).equals(d)) {
                    for (int j = i; j < i + d.length(); j++)
                        bold[j] = true;
                }
            }
        }
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < s.length();) {
            if (bold[i]) {
                res.append("<b>");
                while (i < s.length() && bold[i])
                    res.append(s.charAt(i++));
                res.append("</b>");
            } else
                res.append(s.charAt(i++));
        }
        return res.toString();
    }
X.
https://discuss.leetcode.com/topic/92112/java-solution-boolean-array
Use a boolean array to mark if character at each position is bold or not. After that, things will become simple.
    public String addBoldTag(String s, String[] dict) {
        boolean[] bold = new boolean[s.length()];
        for (int i = 0, end = 0; i < s.length(); i++) {
            for (String word : dict) {
                if (s.startsWith(word, i)) {
                    end = Math.max(end, i + word.length());
                }
            }
            bold[i] = end > i;
        }
        
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (!bold[i]) {
                result.append(s.charAt(i));
                continue;
            }
            int j = i;
            while (j < s.length() && bold[j]) j++;
            result.append("<b>" + s.substring(i, j) + "</b>");
            i = j - 1;
        }
        
        return result.toString();
    }
    for (int i = 0, end = 0; i < s.length(); i++) { // For every character in `s`,
        for (String word : dict) { // For every `word` in `dict`, we test:
            // If substring s[i, i + word.length()] == word, meaning characters between i, 
            // i + word.length() should be `bold`.
            if (s.startsWith(word, i)) {
                // Use variable `end` to store known longest end of current continuous `bold` characters
                end = Math.max(end, i + word.length());
            }
        }
        // If `end` > `i`, meaning character at position `i` is within the current continuous `bold`
        // characters, we mark it as `bold`.
        bold[i] = end > i;
    }
https://discuss.leetcode.com/topic/92130/short-java-solution
    public String addBoldTag(String s, String[] dict) {
        int n = s.length();
        int[] mark = new int[n+1];
        for(String d : dict) {
            int i = -1;
            while((i = s.indexOf(d, i+1)) >= 0) {
                mark[i]++;
                mark[i + d.length()]--;
            }
        }
        StringBuilder sb = new StringBuilder();
        int sum = 0;
        for(int i = 0; i <= n; i++) {
            int cur = sum + mark[i];
            if (cur > 0 && sum == 0) sb.append("<b>");
            if (cur == 0 && sum > 0) sb.append("</b>");
            if (i == n) break;
            sb.append(s.charAt(i));
            sum = cur;
        }
        return sb.toString();
    }
http://www.cnblogs.com/grandyang/p/7043394.html
思路是建一个和字符串s等长的bold布尔型数组,表示如果该字符在单词里面就为true,那么最后我们就可以根据bold数组的真假值来添加标签了。我们遍历字符串s中的每一个字符,把遍历到的每一个字符当作起始位置,我们都匹配一遍字典中的所有单词,如果能匹配上,我们就用i + len来更新end,len是当前单词的长度,end表示字典中的单词在字符串s中结束的位置,那么如果i小于end,bold[i]就要赋值为true了。最后我们更新完bold数组了,就再遍历一遍字符串s,如果bold[i]为false,直接将s[i]加入结果res中;如果bold[i]为true,那么我们用while循环来找出所有连续为true的个数,然后在左右两端加上标签


    string addBoldTag(string s, vector<string>& dict) {
        string res = "";
        int n = s.size(), end = 0;
        vector<bool> bold(n, false);
        for (int i = 0; i < n; ++i) {
            for (string word : dict) {
                int len = word.size();
                if (i + len <= n && s.substr(i, len) == word) {
                    end = max(end, i + len);
                }
            }
            bold[i] = end > i;
        }
        for (int i = 0; i < n; ++i) {
            if (!bold[i]) {
                res.push_back(s[i]);
                continue;
            }
            int j = i;
            while (j < n && bold[j]) ++j;
            res += "<b>" + s.substr(i, j - i) + "</b>";
            i = j - 1;
        }
        return res;
    }

Approach #2 Similar to Merge Interval Problem [Accepted]
We can pick up every word of the dictionary. For every word d of the dictionary chosen currently, say of length length_d, it is obvious that the substrings in s only with length length_d, can match with the d. Thus, instead of blindly checking for d's match with every substring in s, we check only the substrings with length length_d. The matching substrings' indices are again added to the list similar to the last approach.
  • Time complexity : O(l*s*x). Generating list will take O(l*s*x), where x is the average string length of dict.
  • Space complexity : O(s+s*l)res size grows upto O(s) and list size can grow upto O(s*l) in worst case.
    public String addBoldTag(String s, String[] dict) {
        List < int[] > list = new ArrayList < > ();
        for (String d: dict) {
            for (int i = 0; i <= s.length() - d.length(); i++) {
                if (s.substring(i, i + d.length()).equals(d))
                    list.add(new int[] {i, i + d.length() - 1});
            }
        }
        if (list.size() == 0)
            return s;
        Collections.sort(list, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
        int start, prev = 0, end = 0;
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            res.append(s.substring(prev, list.get(i)[0]));
            start = i;
            end = list.get(i)[1];
            while (i < list.size() - 1 && list.get(i + 1)[0] <= end + 1) {
                end = Math.max(end, list.get(i + 1)[1]);
                i++;
            }
            res.append("<b>" + s.substring(list.get(start)[0], end + 1) + "</b>");
            prev = end + 1;
        }
        res.append(s.substring(end + 1, s.length()));
        return res.toString();
    }
https://discuss.leetcode.com/topic/92114/java-solution-same-as-merge-interval
public String addBoldTag(String s, String[] dict) {
        List<Interval> intervals = new ArrayList<>();
        for (String str : dict) {
         int index = -1;
         index = s.indexOf(str, index);
         while (index != -1) {
          intervals.add(new Interval(index, index + str.length()));
          index +=1;
          index = s.indexOf(str, index);
         }
        }
        System.out.println(Arrays.toString(intervals.toArray()));
        intervals = merge(intervals);
        System.out.println(Arrays.toString(intervals.toArray()));
        int prev = 0;
        StringBuilder sb = new StringBuilder();
        for (Interval interval : intervals) {
         sb.append(s.substring(prev, interval.start));
         sb.append("<b>");
         sb.append(s.substring(interval.start, interval.end));
         sb.append("</b>");
         prev = interval.end;
        }
        if (prev < s.length()) {
         sb.append(s.substring(prev));
        }
        return sb.toString();
    }
 
 class Interval {
  int start, end;
  public Interval(int s, int e) {
   start = s;
   end = e;
  }
  
  public String toString() {
   return "[" + start + ", " + end + "]" ;
  }
 }
 
 public List<Interval> merge(List<Interval> intervals) {
        if (intervals == null || intervals.size() <= 1) {
            return intervals;
        }
        Collections.sort(intervals, new Comparator<Interval>(){
            public int compare(Interval a, Interval b) {
                return a.start - b.start;
            }
        });
        
        int start = intervals.get(0).start;
        int end = intervals.get(0).end;
        List<Interval> res = new ArrayList<>();
        for (Interval i : intervals) {
            if (i.start <= end) {
                end = Math.max(end, i.end);
            } else {
                res.add(new Interval(start, end));
                start = i.start;
                end = i.end;
            }
        }
        res.add(new Interval(start, end));
        return res;
    }

Approach #1 Brute Force [Time Limit Exceeded]
  • Time complexity : O(s^3). Generating list of intervals will take O(s^3), where s represents string length.
  • Space complexity : O(s+d+s*l)res size grows upto s and set size will be equal to the size of dict. Here, d refers to the size of dict.And listsize can grow upto O(s*l) in worst case, where l refers to dict size.
    public String addBoldTag(String s, String[] dict) {
        List < int[] > list = new ArrayList < > ();
        Set < String > set = new HashSet < > (Arrays.asList(dict));
        for (int i = 0; i < s.length(); i++) {
            for (int j = i; j < s.length(); j++) {
                if (set.contains(s.substring(i, j + 1)))
                    list.add(new int[] {i, j});
            }
        }
        if (list.size() == 0)
            return s;
        Collections.sort(list, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
        int start, prev = 0, end = 0;
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            res.append(s.substring(prev, list.get(i)[0]));
            start = i;
            end = list.get(i)[1];
            while (i < list.size() - 1 && list.get(i + 1)[0] <= end + 1) {
                end = Math.max(end, list.get(i + 1)[1]);
                i++;
            }
            res.append("<b>" + s.substring(list.get(start)[0], end + 1) + "</b>");
            prev = end + 1;
        }
        res.append(s.substring(end + 1, s.length()));
        return res.toString();
    }

https://discuss.leetcode.com/topic/92130/short-java-solution
    public String addBoldTag(String s, String[] dict) {
        int n = s.length();
        int[] mark = new int[n+1];
        for(String d : dict) {
            int i = -1;
            while((i = s.indexOf(d, i+1)) >= 0) {
                mark[i]++;
                mark[i + d.length()]--;
            }
        }
        StringBuilder sb = new StringBuilder();
        int sum = 0;
        for(int i = 0; i <= n; i++) {
            int cur = sum + mark[i];
            if (cur > 0 && sum == 0) sb.append("<b>");
            if (cur == 0 && sum > 0) sb.append("</b>");
            if (i == n) break;
            sb.append(s.charAt(i));
            sum = cur;
        }
        return sb.toString();
    }
https://www.nowtoshare.com/en/Article/Index/70576

https://blog.csdn.net/magicbean2/article/details/78991317
很常规的思路:找出dict中的每个单词在s中的出现区段interval,然后将这些intervals进行merge,merge之后形成的不重合的intervals就是我们需要插入<b>或者</b>的地方。
    string addBoldTag(string s, vector<string>& dict) {
        vector<pair<int, int>> ranges = findPairs(s, dict);
        ranges = merge(ranges);
        for (auto it = ranges.rbegin(); it != ranges.rend(); ++it) {
            s.insert(it->second, "</b>");
            s.insert(it->first, "<b>");
        }
        return s;
    }
private:
    vector<pair<int, int>> findPairs(string &s, vector<string> &dict) {
        vector<pair<int, int>> res;
        for (string w : dict) {
            int n = w.size();
            for (int i = 0; (i = s.find(w, i)) != string::npos; ++i) {
                res.push_back(pair<int, int>(i, i + n));
            }
        }
        return res;
    }
    vector<pair<int ,int>> merge(vector<pair<int, int>> &a) {
        vector<pair<int, int>> r;
        sort(a.begin(), a.end(), compare);
        for (int i = 0, j = -1; i < a.size(); ++i) {
            if (j < 0 || a[i].first > r[j].second) {
                r.push_back(a[i]);
                ++j;
            }
            else {
                r[j].second = max(r[j].second, a[i].second);
            }
        }
        return r;
    }
    static bool compare(pair<int, int> &a, pair<int, int> &b) {
        return a.first < b.first || a.first == b.first && a.second < b.second;
    }

X. KMP
1. colored数组记录s中是否包含dict中字符串,若包含,将对应位置为'1',否则为'0' 2. 使用KMP字符串匹配算法找出s中包含的dict中字符串的所有位置,将对应colored置为'1' 3. 将colored中连续1用<b></b>包围
   vector<vector<int>> next;
    string colored = "";
    void getNext(vector<string>& dict) {
        int dlen = dict.size();
        next.resize(dlen);
        for (int i = 0; i < dlen; i++) {
            next[i].resize(dict[i].length());
            next[i][0] = -1;
            for (int j = 0; j < dict[i].length() - 1; j++) {
                int k = next[i][j];
                while (k != -1 && dict[i][j] != dict[i][k]) k = next[i][k];
                next[i][j+1] = k + 1;
            }
        }
    }
    void kmp(string s, string t, int index) {
        int i = 0, j = 0;
        while (i < s.length()) {
            if (j == -1 || s[i] == t[j]) {
                i++, j++;
                if (j == t.length()) {
                    while (j != 0) colored[i - j--] = '1';
                    i -= (t.length() - 1);
                }
            }
            else j = next[index][j];
        }
    }
public:
    string addBoldTag(string s, vector<string>& dict) {
        int slen = s.length(), dlen = dict.size();
        next.resize(dlen);
        getNext(dict);
        for (int i = 0; i < slen; i++) colored += "0";
        for (int i = 0; i < dlen; i++) kmp(s, dict[i], i);
        string ans = (colored[0] == '1') ? "<b>" : "";
        for (int i = 0; i < slen; i++) {
            ans += s[i];
            if (colored[i] == '1' && (colored[i + 1] == '0' || colored[i + 1] == '\0')) ans += "</b>";
            else if (colored[i] == '0' && colored[i + 1] == '1') ans += "<b>";
        }
        return ans;
    }

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts