This is a merge interval's variety:

class Solution {
    public String addBoldTag(String s, String[] words) {
        List<int[]> intervals = new ArrayList<>();
        for(int i=0;i<s.length();i++){
            for(String word: words){
                if(s.startsWith(word, i)){
                    intervals.add(new int[]{i, i+word.length()});
                }
            }
        }
        intervals = merge(intervals);
        StringBuilder res = new StringBuilder();
        int index =0;
        for(int[] interval: intervals){
            int x = interval[0];
            int y = interval[1];
            res.append(s.substring(index, x));
            res.append("<b>");
            res.append(s.substring(x, y));
            res.append("</b>");
            index = y;
        }
        res.append(s.substring(index));
        return res.toString();
    }
    
    private List<int[]> merge(List<int[]> intervals){
        List<int[]> res = new ArrayList<>();
        if(intervals.size()==0)
            return res;
        
        int[] inter1 = intervals.get(0);
        for(int i=1;i<intervals.size();i++){
            int[] inter2 = intervals.get(i);
            if(inter1[1]>=inter2[0]){
                int x = Math.min(inter1[0], inter2[0]);
                int y = Math.max(inter1[1], inter2[1]);
                int[] newInterval = new int[]{x, y};
                inter1 = newInterval;
            }else{
                res.add(inter1);
                inter1= inter2;
            }
        }
        res.add(inter1);
        return res;
    }
}

 

posted on 2022-04-14 02:29  阳光明媚的菲越  阅读(22)  评论(0编辑  收藏  举报