题目链接:https://www.dotcpp.com/oj/problem1453.html

    贪心策略:如果当前位置的字符不匹配,即 src[i] != target[i],将src中的位置 i 和 i+1 的字符进行翻转,用局部最优代替全局最优(但是这种贪心策略为什么可以成立,尚未能给出证明),记录进行翻转次数即为答案。

    1. import java.util.*;
    2. public class Main{
    3. public static void main(String[] args) {
    4. Scanner sc = new Scanner(System.in);
    5. char[] src = sc.next().toCharArray();
    6. char[] target = sc.next().toCharArray();
    7. int ans = 0;
    8. for(int i = 0; i < src.length-1; i++){
    9. if(src[i] != target[i]) {
    10. ans++;
    11. src[i] = src[i] == '*' ? 'o' : '*';
    12. src[i+1] = src[i+1] == '*' ? 'o' : '*';
    13. }
    14. }
    15. System.out.println(ans);
    16. }
    17. }