首页 > 其他 > 详细

LeetCode Add Bold Tag in String

时间:2017-10-20 09:49:26      阅读:353      评论:0      收藏:0      [点我收藏+]

原题链接在这里: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:

 1 class Solution {
 2     public String addBoldTag(String s, String[] dict) {
 3         if(s == null || s.length() == 0){
 4             return s;
 5         }
 6         
 7         boolean [] mark = new boolean[s.length()];
 8         for(String word : dict){
 9             for(int i = 0; i<=s.length()-word.length(); i++){
10                 if(s.substring(i, i+word.length()).equals(word)){
11                     for(int j = i; j<i+word.length(); j++){
12                         mark[j] = true;
13                     }
14                 }
15             }
16         }
17         
18         int i = 0;
19         StringBuilder sb = new StringBuilder();
20         while(i<mark.length){
21             if(mark[i]){
22                 sb.append("<b>");
23                 while(i<mark.length && mark[i]){
24                     sb.append(s.charAt(i++));
25                 }
26                 sb.append("</b>");
27             }else{
28                 sb.append(s.charAt(i++));
29             }
30         }
31         return sb.toString();
32     }
33 }

 

LeetCode Add Bold Tag in String

原文:http://www.cnblogs.com/Dylan-Java-NYC/p/7697042.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!