字符串的最大子序列

假设是找连续的子序列,比方说  abcdefg 和1234abc45d,这两个序列,连续的最大子序列就是abc,

假设是找离散的子序列,那么上面的例子里的最大子就是abcd了。


这个题目是我看海涛桑德博客发现的,感觉貌似见过,但觉得很奇怪为什么是dp,后来我发现是离散的那种情况。

类似的我做过一个求字符串相似度的题目,其实就是这种最大离散的序列的问题。貌似是一个百度的面试题目。


今天又做了一遍:连续的话是一个循环,不断尝试做匹配就可以了,离散的情况是一个dp

//找出这两个字符串中的子序列,例子中就是ghj882
//假设可以不连续,就成了找字符相似度那道题目了,就是个dp
//假设按照连续来做就是一个循环
public class Maxsamestring {
    public static void main(String[] args) {
        String str1 = "asdfghj882kl";
        String str2 = "1qasdfrtghj88291";
        Maxsamestring instance = new Maxsamestring();
        int max = instance.CaculateMaxSameString(str1, str2);
        System.out.print(max);
    }
    int CaculateMaxSameString(String str1, String str2) {
        int firstLength = str1.length();
        int maxMatch = 0;
        int currentMatch = 0;
        for (int i = 0; i < firstLength; i++) {
            currentMatch = getMaxMatch(i, str1, str2);
            if (currentMatch > maxMatch)
                maxMatch = currentMatch;
        }
        return maxMatch;
    }
    
    private int getMaxMatch(int firstStringBegin, String str1, String str2) {
        int matchLenght = 0;
        Boolean canMatchWithSecond = false;
        do {
            matchLenght++;
            String firstTryMatch = str1.substring(firstStringBegin,
                    firstStringBegin + matchLenght);
            canMatchWithSecond = tryMatch(firstTryMatch, str2);
        } while (canMatchWithSecond);
        return matchLenght-1;
    }
    
    private Boolean tryMatch(String firstTryMatch, String str2) {
        if (str2.contains(firstTryMatch))
            return true;
        else
            return false;
    }
}

str1='asdgfgyi'
str2='asdgfhjk'
str1Len=len(str1)
str2Len=len(str2)

def findMin(x,y,z):
    if x>=y and z>=y:
        return y;
    elif x>=z and y>=z:
        return z;
    else:
        return x;

def getDiff(str1SatrtPos,str2StartPos):
    if str1SatrtPos<str1Len and str2StartPos<str2Len:
        if cmp(str1[str1SatrtPos],str2[str2StartPos])==0:
            return getDiff(str1SatrtPos+1,str2StartPos+1)
        else:
            ifDeleteStr1=getDiff(str1SatrtPos+1,str2StartPos)+1;
            ifDeleteStr2=getDiff(str1SatrtPos,str2StartPos+1)+1;
            ifDeleteStrBoth=getDiff(str1SatrtPos+1,str2StartPos+1)+1;
            return findMin(ifDeleteStr1,ifDeleteStr2,ifDeleteStrBoth)

    else:
        if str1SatrtPos==str1Len and str2StartPos==str2Len:
            return 0;
        elif str1SatrtPos==str1Len and str2StartPos!=str2Len:
            return len(str2);
        else:
            return len(str1);


diff=getDiff(0,0);
print diff



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值