您好,欢迎访问代理记账网站
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

812. 字符串中的加粗单词

812. 字符串中的加粗单词

 

 

给定一组关键字“words”和一个字符串“S”,将所有关键字以S粗体显示。 <b>  和  </b> 标记之间的任何字母都将加粗。
返回的字符串应该使用尽可能少的标签,当然这些标签应该组成一个有效的组合。

样例

样例 1:
输入:
["ab", "bc"]
"aabcd"
输出:
"a<b>abc</b>d"
 
解释:
"a<b>a<b>b</b>c</b>d" 用了更多的标签,所以不对
样例 2:
输入:
["bcccaeb","b","eedcbda","aeebebebd","ccd","eabbbdcde","deaaea","aea","accebbb","d"]
"ceaaabbbedabbecbcced"
输出:
"ceaaa<b>bbb</b>e<b>d</b>a<b>bb</b>ec<b>b</b>cce<b>d</b>"

注意事项

  • words  长度在 [0, 50] .
  • words[i]  长度在  [1, 10] .
  • S  长度在  [0, 500] .
  • words[i]  和  S  由小写字母组成
 
public class Solution {
    /**
     * @param words: the words
     * @param S: the string
     * @return: the string with least number of tags
     */
    public String boldWords(String[] words, String S) {
        // Write your code here
       StringBuilder stringBuffer = new StringBuilder();
            boolean[] sum = new boolean[S.length()];
            char[] chars=S.toCharArray();
            for (String word : words) {
                char[] chars1 = (word.toCharArray());
                for (int j = 0; j <= chars.length-chars1.length; j++) {
                    boolean has = false;
                    for (int k = 0; k < chars1.length; k++) {
                        if (chars[j+k] == chars1[k]) {
                            has = true;
                        }else{
                            has = false;
                            break;
                        }
                    }
                    if (has){
                        for (int k = j; k <j+chars1.length; k++) {
                            sum[k]=true;
                        }
                    }
                }
            }
            boolean flag = false;
            for (int i = 0; i < sum.length; i++) {
                // System.out.println(i+","+sum[i]);
                if (sum[i]) {
                    if (!flag) {
                        // System.out.println(S.charAt(i));
                        stringBuffer.append("<b>");
                        flag = true;
                    }
                } else {
                    if (flag) {
                        // System.out.println(S.charAt(i));
                        stringBuffer.append("</b>");
                        flag = false;
                    }
                }
                stringBuffer.append(S.charAt(i));
            }
            if (flag) {
                stringBuffer.append("</b>");
            }
            return stringBuffer.toString();
    }
}
 

分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进