616. Add Bold Tag in String
作者:互联网
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; } }
标签:int,res,616,inter1,inter2,intervals,Add,Tag,List 来源: https://www.cnblogs.com/feiflytech/p/16142901.html