字符串算法大全

1、LCS

def lcs(a,b):
    lena=len(a)
    lenb=len(b)
    c=[[0 for i in range(lenb+1)] for j in range(lena+1)]
    flag=[[0 for i in range(lenb+1)] for j in range(lena+1)]
    for i in range(lena):
        for j in range(lenb):
            if a[i]==b[j]:
                c[i+1][j+1]=c[i][j]+1
                flag[i+1][j+1]='ok'
            elif c[i+1][j]>c[i][j+1]:
                c[i+1][j+1]=c[i+1][j]
                flag[i+1][j+1]='left'
            else:
                c[i+1][j+1]=c[i][j+1]
                flag[i+1][j+1]='up'
    return c,flag

def printLcs(flag,a,i,j):
    if i==0 or j==0:
        return
    if flag[i][j]=='ok':
        printLcs(flag,a,i-1,j-1)
        print(a[i-1],end='')
    elif flag[i][j]=='left':
        printLcs(flag,a,i,j-1)
    else:
        printLcs(flag,a,i-1,j)
        
a='ABCBDAB'
b='BDCABA'
c,flag=lcs(a,b)
for i in c: 
    print(i)
print('')
for j in flag:
    print(j)
print('')
printLcs(flag,a,len(a),len(b))
print('')

 2、CSD:

1、s1.length==0,return s2.length;

2、s2.length==0,return s1.length;

3、if  s1.charat(i)==s2.charat(j),res[i][j]=res[i-1][j-1]

  else  res[i][j]=min(res[i-1][j],res[i][j-1],res[i-1][i-1]) +1 

 

 

3、LIS:

 

def longest_increasing_subsequence(tmp_str):
    tmp_len = len(tmp_str);
    LIS = [1 for i in range(tmp_len)];
    for i in range(tmp_len):
        j=0;
        while j <= i:
            if (tmp_str[i] > tmp_str[j]) and (LIS[i] < LIS[j]+1):
                LIS[i] = LIS[j]+1;
            j = j+1;
    return max(LIS);

 

posted @ 2016-08-07 17:55  pku_smile  阅读(213)  评论(0编辑  收藏  举报