LeetCode 758: Bold Words in String Solution
Master LeetCode problem 758 (Bold Words in String), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
758. Bold Words in String
Problem Explanation
Explanation:
Given a string s and a list of strings words, we need to bold all occurrences of the words in s. A word is bold if it appears in s and all letters in the word are bolded. The objective is to return the final bolded string.
To solve this problem, we can iterate through all substrings of s and check if each substring matches any word in words. If a match is found, we mark the corresponding characters in s as bold. To mark the characters as bold, we maintain a boolean array bold of the same length as s, where bold[i] is true if the character at index i in s is bold, and false otherwise.
The steps to solve the problem are as follows:
- Initialize the
boldarray withfalsefor each character ins. - Iterate through all substrings of
sand check if each substring matches any word inwords. - If a match is found, update the
boldarray to mark the characters as bold. - Construct the final bolded string using the
boldarray.
The time complexity of this approach is O(nml), where n is the length of the input string s, m is the number of words in the input list words, and l is the average length of words in words. The space complexity is O(n) to store the bold array.
: :
Solution Code
class Solution {
public String boldWords(String[] words, String s) {
boolean[] bold = new boolean[s.length()];
for (String word : words) {
int index = s.indexOf(word, 0);
while (index != -1) {
for (int i = index; i < index + word.length(); i++) {
bold[i] = true;
}
index = s.indexOf(word, index + 1);
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
if (bold[i] && (i == 0 || !bold[i - 1])) {
sb.append("<b>");
}
sb.append(s.charAt(i));
if (bold[i] && (i == s.length() - 1 || !bold[i + 1])) {
sb.append("</b>");
}
}
return sb.toString();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 758 (Bold Words in String)?
This page provides optimized solutions for LeetCode problem 758 (Bold Words in String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 758 (Bold Words in String)?
The time complexity for LeetCode 758 (Bold Words in String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 758 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 758 in Java, C++, or Python.