758. Bold Words in String
leetcode medium
#array#csharp#leetcode#medium#string
Task
При наличии массива ключевых слов и строки a выделите все ключевые слова [i] жирным шрифтом. Все буквы между тегами <b> и </b> выделяются жирным шрифтом.
Возвращает после добавления тегов, выделенных жирным шрифтом. Возвращаемая строка должна содержать как можно меньшее количество тегов, и теги должны образовывать допустимую комбинацию.
Пример:
Input: words = ["ab","bc"], s = "aabcd"
Output: "a<b>abc</b>d"
C# solution
matched/originalpublic class Solution {
public string AddBoldTags(string[] keywords, string s) {
int n = s.Length;
bool[] bold = new bool[n];
foreach (string word in keywords) {
int start = s.IndexOf(word);
while (start != -1) {
for (int i = start; i < start + word.Length; i++) {
bold[i] = true;
}
start = s.IndexOf(word, start + 1);
}
}
var result = new StringBuilder();
int j = 0;
while (j < n) {
if (bold[j]) {
result.Append("<b>");
while (j < n && bold[j]) {
result.Append(s[j]);
j++;
}
result.Append("</b>");
} else {
result.Append(s[j]);
j++;
}
}
return result.ToString();
}
}C++ solution
auto-draft, review before submit#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public string AddBoldTags(vector<string> keywords, string s) {
int n = s.size();
bool[] bold = new bool[n];
foreach (string word in keywords) {
int start = s.IndexOf(word);
while (start != -1) {
for (int i = start; i < start + word.size(); i++) {
bold[i] = true;
}
start = s.IndexOf(word, start + 1);
}
}
var result = new StringBuilder();
int j = 0;
while (j < n) {
if (bold[j]) {
result.Append("<b>");
while (j < n && bold[j]) {
result.Append(s[j]);
j++;
}
result.Append("</b>");
} else {
result.Append(s[j]);
j++;
}
}
return result.ToString();
}
}Java solution
auto-draft, review before submitimport java.util.*;
import java.math.*;
// Auto-generated Java draft from the C# solution. Review API differences before LeetCode submit.
public class Solution {
public String AddBoldTags(String[] keywords, String s) {
int n = s.length;
boolean[] bold = new boolean[n];
foreach (String word in keywords) {
int start = s.IndexOf(word);
while (start != -1) {
for (int i = start; i < start + word.length; i++) {
bold[i] = true;
}
start = s.IndexOf(word, start + 1);
}
}
var result = new StringBuilder();
int j = 0;
while (j < n) {
if (bold[j]) {
result.Append("<b>");
while (j < n && bold[j]) {
result.Append(s[j]);
j++;
}
result.Append("</b>");
} else {
result.Append(s[j]);
j++;
}
}
return result.ToString();
}
}JavaScript solution
matched/originalfunction addBoldTags(keywords, s) {
const n = s.length;
const bold = Array(n).fill(false);
for (const word of keywords) {
let start = s.indexOf(word);
while (start !== -1) {
for (let i = start; i < start + word.length; i++) {
bold[i] = true;
}
start = s.indexOf(word, start + 1);
}
}
let result = '';
let i = 0;
while (i < n) {
if (bold[i]) {
result += '<b>';
while (i < n && bold[i]) {
result += s[i];
i++;
}
result += '</b>';
} else {
result += s[i];
i++;
}
}
return result;
}Python solution
matched/originaldef addBoldTags(keywords, s):
n = len(s)
bold = [False] * n
for word in keywords:
start = s.find(word)
while start != -1:
for i in range(start, start + len(word)):
bold[i] = True
start = s.find(word, start + 1)
result = []
i = 0
while i < n:
if bold[i]:
result.append("<b>")
while i < n and bold[i]:
result.append(s[i])
i += 1
result.append("</b>")
else:
result.append(s[i])
i += 1
return "".join(result)Go solution
matched/originalpackage main
import (
"strings"
)
func addBoldTags(keywords []string, s string) string {
n := len(s)
bold := make([]bool, n)
for _, word := range keywords {
start := strings.Index(s, word)
for start != -1 {
for i := start; i < start+len(word); i++ {
bold[i] = true
}
start = strings.Index(s, word, start+1)
}
}
var result strings.Builder
i := 0
for i < n {
if bold[i] {
result.WriteString("<b>")
for i < n && bold[i] {
result.WriteByte(s[i])
i++
}
result.WriteString("</b>")
} else {
result.WriteByte(s[i])
i++
}
}
return result.String()
}Explanation
Algorithm
Создайте массив для хранения флагов, указывающих, какие символы в строке a должны быть выделены жирным шрифтом.
Пройдите по каждому ключевому слову и отметьте соответствующие позиции в массиве флагов.
Постройте результирующую строку, добавляя теги <b> и </b> на основе массива флагов.
😎