思路
每次只能翻转相邻两枚硬币,因此开始状态与目标状态的不同之处一定是偶数个
对于每两个不同之处单独进行翻转,翻转次数一定是位置之差
因此只需遍历一遍将这些差相加即可,时间复杂度O(n)
java 代码
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
char[] start = br.readLine().toCharArray();
char[] end = br.readLine().toCharArray();
int temp = -1, res = 0;
for (int i = 0; i < start.length; i++) {
if (start[i] != end[i]) {
if (temp == -1) {
temp = i;
} else {
res += i - temp;
temp = -1;
}
}
}
bw.write(String.valueOf(res));
bw.flush();
bw.close();
}
}