JavaScript solution marking bold characters


  • 0
    var addBoldTag = function(s, dict) {
        const bold = new Array(s.length);
        for (let sub of dict) {
            let found = -1;
            let prevBold = 0;
            while ((found = s.indexOf(sub, found + 1)) !== -1) {
                for (let i = Math.max(prevBold, found); i < found + sub.length; i++) {
                    bold[i] = 1;
                }
                prevBold = found + sub.length;
            }
        }
        let res = '';
        let open = false;
        for (let i = 0; i < s.length; i++) {
            if (bold[i] && !open) {
                open = true;
                res += '<b>';
            } else if (!bold[i] && open) {
                open = false;
                res += '</b>';
            }
            res += s[i];
        }
        return open ? res + '</b>' : res;
    };
    

  • 0

    @loctn said in JavaScript O(mn) solution marking bold characters:

    O(mn)

    What are your m and n?


  • 0

    @StefanPochmann whoops s.length and dict.length. Times the maximum substring in the worst case (say s = 'aaa...aa' and dict = ['aa', 'aaa', ...]). What do you think?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.