Bold Words In String


  • 0

    Click here to see the full article post


  • 0

    for the java versioN: Get rid of match function, you never called it.


  • 0
    T

    My straight-forward Python Solution with comments

    def boldWords(self, words, s):
    """
    :type words: List[str]
    :type S: str
    :rtype: str
    """
    # Step 1: Find the positions of chars that will need to be marked bold.
    # do a basic substring search
    # let the mask be an array equal to length of s
    mask = [False]*len(s)
    for w in words:
    for i in xrange(len(s)):
    if s[i:i+len(w)] == w:
    for j in range(i, i+len(w)):
    mask[j] = True
    #print mask

        # Step 2: Identify groups. 
        # mask = [False, True, True, True, False, False, False, True, True, True, True]
        # once you find a "true" continue until you fnd the first false and return both start and end positions. 
        # Build a new string 
        # try to find how to distinguish between the start and end of a "true" group.
        # Start :  False, True 
        # End : True, False
        ans = []
        for i in xrange(len(s)):
            if (mask[i] and (i == 0 or not mask[i-1])): # starting True
                ans.append("<b>")
            ans.append(s[i])
            if ( mask[i] and (i== len(s)-1 or not mask[i+1])): # ending True
                ans.append("</b>")
        return "".join(ans)

Log in to reply
 

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