616. Add Bold Tag in 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].

一刷
题解:

  1. 如果有overlap, 用bold标志符包住他们的并集
  2. 如果连续,也是一起包住。

首先有一种bruteforce的解法。 首先我们对字符串的每个位置对每个字典中的word进行是否startwith的判断。

class Solution {
    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());
                }
            }
            //judge whether this index is bold
            bold[i] = end>i;
            
        }
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<s.length(); i++){
            if(!bold[i]){
                sb.append(s.charAt(i));
                continue;
            }
            
            int j=i;
            while(j<s.length() && bold[j]) j++;
            sb.append("<b>").append(s.substring(i,j)).append("</b>");
            i = j-1;
        }
        return sb.toString();
    }
}

Speed up
用indexof找出interval
然后用interval求并集的方式,比如[1,2,3]那么在1处++, 在4处--。然后根据sum判断interval是否结束。

class Solution {
    public String addBoldTag(String s, String[] dict) {
        if(dict.length == 0 || s==null || s.length() == 0) return s;
        int n = s.length();
        int[] mark = new int[n+1];
        for(String word:dict){
            int i=-1;
            while((i=s.indexOf(word, i+1))>=0){
                mark[i]++;
                mark[i+word.length()]--;
            }
        }
        
        int prev = 0;
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<=n; i++){
            int cur = prev + mark[i];
            if(prev == 0 && cur>0) sb.append("<b>");
            if(prev>0 && cur==0) sb.append("</b>");
            if(i==n) break;
            sb.append(s.charAt(i));
            prev = cur;
        }
        return sb.toString();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • 自古到今,有太多的人歌颂坚持,甚至,把此行为本身上升到了做人的境界。 在我看来,其实不然。 我认为,坚持这个行为,...
    冰冷的夜阅读 480评论 0 0
  • 当我假宽恕的时候我是伤心的,我看到她左眼中有泪光闪烁,我想知道你为什伤心。 当我假宽恕的时候我是勇于担当的,我看到...
    sui想阅读 405评论 0 0
  • 欣赏感谢自己送给自己
    水玲珑英子阅读 167评论 1 0