[LeetCode 616] Add Bold Tag in String

本文介绍了一种算法,用于在给定的字符串中查找并加粗包含在字典中的子字符串。通过使用set数据结构来高效查找和标记,确保了即使在子字符串重叠或连续时也能正确处理。

Given a string s and a list of strings dict, you need to add a closed pair of bold tag and 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

Input: 
s = "abcxyz123"
dict = ["abc","123"]
Output:
"<b>abc</b>xyz<b>123</b>"
Input: 
s = "aaabbcc"
dict = ["aaa","aab","bc"]
Output:
"<b>aaabbc</b>c"

Notice

The given dict won't contain duplicates, and its length won't exceed 100.
All the strings in input have length in range [1, 1000].

分析

这道题可以使用set存放所有的word。使用一个另外的数组isTag记录s的每一位是否是需要加粗的。然后遍历s的子串,如果发现子串在dict中,则将isTag对应的位设置为true。

在遍历的时候我们可以使用另外一个set记录所有的word的长度,每次寻找子串是否在dict中时,我们先从最长的长度开始查找,如果找到了,接下来的就不用寻找了。

这道题当时想用TrieTree存放dict中的word,但是发现内存会爆掉。所以最后还是用set进行存放的。

Code

class Solution {
public:
    /**
     * @param s: a string
     * @param dict: a list of strings
     * @return: return a string
     */

    string addBoldTag(string &s, vector<string> &dict) {
        // write your code here

        int dictLen = dict.size();
        set<string> words;
        set<int> lens;
        int maxLen = 0;
        for(int i = 0; i < dictLen; i ++)
        {
            words.insert(dict[i]);
            lens.insert(dict[i].size());
        }

        vector<bool> isTag(s.size(), false);
        for (int i = 0; i < s.size(); i ++)
        {
            set<int>::reverse_iterator it;
            for (it = lens.rbegin(); it != lens.rend(); it ++)
            {
                if (words.find(s.substr(i, *it)) != words.end())
                {
                    break;
                }
            }
            if (it != lens.rend())
            {
                for (int j = i; j < i + *it; j ++)
                    isTag[j] = true;
            }
        }

        string res;
        bool add = false;
        for (int i = 0; i < s.size(); i ++)
        {
            if (!add && isTag[i])
            {
                res += "<b>";
                res.push_back(s[i]);
                add = true;
            }
            else if (add && !isTag[i])
            {
                res += "</b>";
                res.push_back(s[i]);
                add = false;
            }
            else
            {
                res.push_back(s[i]);
            }
        }
        if (add)
            res += "</b>";

        return res;
    }
};

运行效率

Your submission beats 39.17% Submissions!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值