最少前缀操作问题--感受不到动态规划,怎么办怎么办

题目:

标签:动态规划(应该是双指针的,不理解)

小U和小R有两个字符串,分别是S和T,现在小U需要通过对S进行若干次操作,使其变成T的一个前缀。操作可以是修改S的某一个字符,或者删除S末尾的字符。现在你需要帮助小U计算出,最少需要多少次操作才能让S变成T的前缀。


测试样例

样例1:

输入:S = "aba", T = "abb"
输出:1

样例2:

输入:S = "abcd", T = "efg"
输出:4

样例3:

输入:S = "xyz", T = "xy"
输出:1

样例4:

输入:S = "hello", T = "helloworld"
输出:0

样例5:

输入:S = "same", T = "same"
输出:0


不行,感觉我的脑子废了,第一遍是用动态规划解决该问题,但是!wrong!参考了下那个Al的想法是了下,感觉我的智商堪忧,这个怎么也不是动态规划的题解。

public class Main {
    public static int solution(String S, String T) {
        //最少的前缀操作次数,说实话,做了这道题目感受不到一点动态规划的感觉

        int deleteCount = 0;
        if(S.length() > T.length()){
            deleteCount = S.length() -  T.length();
        }
        
        int i = 0;
        int j = 0;
        int count = 0;

        while(i < Math.min(S.length(),T.length())){
            if(S.charAt(i) != T.charAt(j)){
                count ++;
            }
            i++;
            j++;
        }
        return count + deleteCount;
    }

    public static void main(String[] args) {
        System.out.println(solution("aba", "abb") == 1);
        System.out.println(solution("abcd", "efg") == 4);
        System.out.println(solution("xyz", "xy") == 1);
        System.out.println(solution("hello", "helloworld") == 0);
        System.out.println(solution("same", "same") == 0);
    }
}

你可能感兴趣的:(算法,java,动态规划)