原题链接在这里:https://leetcode.com/problems/add-bold-tag-in-string/description/

题目:

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].

题解:

类似Merge Intervals. 标记出dict中每个word所在s的起始结束位置. sort后merge.

或者直接用boolean array来标记s的当前char是否出现在dict中word所在s的substring内.

Time Complexity: O(dict.length*s.length()*x). x是dict中word的平均长度.

Space: O(s.length()).

AC Java:

 class Solution {
public String addBoldTag(String s, String[] dict) {
if(s == null || s.length() == 0 || dict == null || dict.length == 0){
return s;
} boolean [] mark = new boolean[s.length()];
for(String word: dict){
for(int i = 0; i<=s.length()-word.length(); i++){
if(s.startsWith(word, i)){
Arrays.fill(mark, i, i+word.length(), true);
}
}
} int i = 0;
StringBuilder sb = new StringBuilder();
while(i<mark.length){
if(mark[i]){
sb.append("<b>");
while(i<mark.length && mark[i]){
sb.append(s.charAt(i++));
} sb.append("</b>");
}else{
sb.append(s.charAt(i++));
}
} return sb.toString();
}
}

最新文章

  1. ASP.NET MVC5+EF6+EasyUI 后台管理系统(38)-Easyui-accordion+tree漂亮的菜单导航
  2. 【无私分享:ASP.NET CORE 项目实战(第十章)】发布项目到 Linux 上运行 Core 项目
  3. markdown 标识语言
  4. font-weight -- 定义字体的粗细
  5. 使用批处理(bat)脚本对目录树下同种性质的目录或文件进行处理
  6. Swift - 初始化Initialization
  7. JAVA利用enum结合testng做数据驱动示例
  8. C#中判断子窗体是否存在
  9. CentOS下修复grub引导程序
  10. C++ 二叉树遍历实现
  11. Unity3D 之射线检测
  12. POJ3080 - Blue Jeans(KMP+二分)
  13. Examples_08_08
  14. 使用jQuery操作元素的属性与样式
  15. v-bind特性
  16. Java基础练习1(数据类型转换)
  17. c/c++ llinux epoll系列4 利用epoll_wait实现非阻塞的connect
  18. lower_bound函数与upper_bound函数
  19. eclipse打Jar包问题
  20. php添加pdo_mysql.so的扩展

热门文章

  1. 002. MySQL复制操作
  2. CF960G(第一类斯特林数)
  3. VRChat简易教程4-使用VRC的接口实现物体的移动(VRC的action和trigger接口)
  4. JavaEE之动态代理
  5. JS Object To C# ASP.Net ModelBind
  6. spring学习(6)
  7. ps(笔记)
  8. Linux 任务控制(bg job fg nohup &amp;) (转)
  9. 牛客比赛-状压dp
  10. is(&#39;:visible&#39;)