阿里2020/8/3笔试题(二)

接上一篇文章,阿里笔试题第二题。使用了马后炮实现法,考场上实现不了就考完查资料再实现。

第二题:给定一个字符串,字符串只包含abcdef 6个字母,求满足下列规则的最长子序列的长度:

1、a必须在c,e前,c必须在e前;

2、b必须在d,f前, d必须在f前;

两个条件互相独立,因此可以将字符串拆为两个子串,一个子串只含a,c,e三个字母,另一个子串只含b,d,f三个字母,然后分别求两个字串的最长子序列的长度,再求两个长度之和即可。解法与LeetCode第300题解法相同(注意LeetCode第300题为最长上升子序列,而本题其实为最长不下降子序列)。

LeetCode第300题地址:最长上升子序列

Talk is cheap, show me the code.

 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class ALiTest2 {
    //此方法为辅助方法,为了求字符串符合条件的最大子串
    private static int helper(ArrayList<Character> list){
        if(list.size() == 0){   //因为将输入字符穿拆成了两串,因此如果原字符串完全不含a,c,e或b,d,f的话,会有一串子串长度为零
            return 0;
        }
        int[] dp = new int[list.size()];
        Arrays.fill(dp,1);
        int max = 1;    //如果两串都有长度,则初始化最大子串长度为1
        for (int i = 1; i < list.size(); i++) {         //动态规划
            for (int j = 0; j < i; j++) {
                if (list.get(i) >= list.get(j)){        //字符可以直接比较大小
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
            max = Math.max(dp[i], max);
        }
        return max;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        char[] chars = s.toCharArray();     //将字符串转化为字符数组
        ArrayList<Character> list1 = new ArrayList<>();
        ArrayList<Character> list2 = new ArrayList<>();
        for (char c : chars) {               //将字符串分为两个子串
            if(c == 'a' || c == 'c' || c == 'e'){
                list1.add(c);
            }
            if(c == 'b' || c == 'd' || c == 'f'){
                list2.add(c);
            }
        }
        System.out.println(helper(list1) + helper(list2));
        sc.close();
    }
}

我只使用了最笨的动态规划方法,还有一种二分的优化动态规划解法,详情见:动态规划+二分查找

 

猜你喜欢

转载自blog.csdn.net/DebugMyself/article/details/107825935
今日推荐