java solution


  • 0
    2
    public class Solution {
        public String addBoldTag(String s, String[] dict) {
            boolean[] bold = new boolean[s.length()];
            for (String d : dict) {
                List<Integer> l = find(s, d);
                fill(bold, l, d.length());
            }
            return boldString(s, bold);
        }
        
        private List<Integer> find(String s, String t) {
            List<Integer> l = new ArrayList<>();
            int i = 0;
            while (i < s.length()) {
                i = s.indexOf(t, i);
                if (i == -1) {
                    break;
                }
                l.add(i);
                i++;
            }
            return l;
        }
        
        private void fill(boolean[] bold, List<Integer> l, int length) {
            int last = 0;
            for (int i : l) {
                int end = Math.min(i + length, bold.length);
                for (int j = Math.max(last, i); j < end; j++) {
                    bold[j] = true;
                }
                last = i + length;
            }
        }
        
        private String boldString(String s, boolean[] bold) {
            StringBuilder sb = new StringBuilder();
            int i = 0;
            while (i < s.length()) {
                if (!bold[i]) {
                    sb.append(s.charAt(i));
                    i++;
                } else {
                    int start = i;
                    while (i < s.length() && bold[i]) {
                        i++;
                    }
                    sb.append("<b>" + s.substring(start, i) + "</b>");
                }
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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