Java solution, [merging intervals][15ms]


  • 0
    public class Solution {
        public String addBoldTag(String s, String[] dict) {
    
            // Save a space for the tag added at the end
            int[] tagArr = new int[s.length() + 1];
    
            // Mark the indexes for all occurrences of dict strings in the input string
            // +1 if <b>, and -1 if </b>
            for (String str : dict) {
                int startIndex = s.indexOf(str);
                while (startIndex != -1) {
                    int endIndex = startIndex + str.length();
                    tagArr[startIndex] += 1;
                    tagArr[endIndex] += -1;
                    startIndex = s.indexOf(str, startIndex + 1);
                }
            }
    
            int sum = 0;
            StringBuilder sb = new StringBuilder();
            for (int i=0; i<s.length(); ++i) {
                int preSum = sum;
                sum += tagArr[i];
    
                if (preSum == 0 && preSum < sum ){
                    // "0 -> positive" means <b>
                    sb.append("<b>");
                } else if (sum == 0 && preSum > sum) {
                    // "positive -> 0" means </b>
                    sb.append("</b>");
                }
    
                sb.append(s.charAt(i));
            }
    
            // Don't forget the last </b> if any
            if (tagArr[tagArr.length - 1] < 0) sb.append("</b>");
    
            return sb.toString();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.