[Algorithm]microsoft-a-string-into-sub-strings-with-additional-info-within-limited-length

https://leetcode.com/discuss/interview-question/439260/microsoft-phone-split-a-string-into-sub-strings-with-additional-info-within-limited-length

Extend: append notation such as " (1 of 12)" and strings are not longer than the limit even after the notation.

Length limit: 39. Input: The quick brown fox jumps over a lazy dogThe quick brown fox jumps over a lazy dogThe quick brown fox jumps over a lazy dogThe quick brown fox jumps over a lazy dogThe quick brown fox jumps over a lazy dogThe quick brown fox jumps over a lazy dogThe quick brown fox jumps over a lazy dogThe quick brown fox jumps over a lazy dogThe quick brown fox jumps over a lazy dog

Result should be:
The quick brown fox jumps (1 of 14)
over a lazy dogThe quick (2 of 14)
brown fox jumps over a lazy (3 of 14)
dogThe quick brown fox jumps (4 of 14)
over a lazy dogThe quick (5 of 14)
brown fox jumps over a lazy (6 of 14)
dogThe quick brown fox jumps (7 of 14)
over a lazy dogThe quick (8 of 14)
brown fox jumps over a lazy (9 of 14)
dogThe quick brown fox jumps (10 of 14)
over a lazy dogThe quick (11 of 14)
brown fox jumps over a lazy (12 of 14)
dogThe quick brown fox jumps (13 of 14)
over a lazy dog (14 of 14)

def convert(s,limit):
    def check(sub,limit,guess):
        cur=0
        ln=1
        i=0
        while i<len(sub):
            ltxt=len(sub[i])+1
            cur+=ltxt
            tail=len("( " + str(ln) + " of " + str(guess) +")")
            if cur+tail>limit:
                ln+=1
                cur=0
            else:
                i+=1

        return ln

    l=0
    r=len(s)-1
    sub=s.split()
    #print r
    while l<r:
        mid=(l+r)/2
        ret=check(sub,limit,mid)
        #print ret,mid
        if ret>mid:
            l=mid+1
        else:
            r=mid
    #print r
    i=0
    ret=[]
    cur=0
    ln=1
    t=""
    while i<len(sub):
        txt=sub[i]+" "
        cur+=len(txt)
        tail="(" + str(ln) + " of " + str(r) +")"
        #print tail
        #print cur,len(tail)
        if cur+len(tail)>limit:
            ln+=1
            ret.append(t+tail)
            #print ret
            cur=0
            t=""

        else:
            #cur+=len(txt)
            t+=txt
            i+=1

    #print ret
    #ln=1
    ret.append(t+tail)
    return ret

s="The quick brown fox jumps over a lazy dogThe quick brown fox jumps over a lazy dogThe quick brown fox jumps over a lazy dogThe quick brown fox jumps over a lazy dogThe quick brown fox jumps over a lazy dogThe quick brown fox jumps over a lazy dogThe quick brown fox jumps over a lazy dogThe quick brown fox jumps over a lazy dogThe quick brown fox jumps over a lazy dog"

print convert(s,39)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章