【算法】程序猿不写代码是不对的78

xiaoxiao2021-02-28  92

package com.kingdz.algorithm.time201707; /** * <pre> * 字符链条 * * http://judgecode.com/problems/1010 * * Little Tom wants to change all the words into palindromes. * To do this, he follows 2 rules: * (a) He can reduce the value of a letter, e.g. he can change 'd' to 'c', but he cannot change 'c' to 'd'. * (b) In order to form a palindrome, if he has to repeatedly reduce the value of a letter, he can do it until the letter becomes 'a'. * Once a letter has been changed to 'a', it can no longer be changed. * Each reduction in the value of any letter is counted as a single operation. * Find the minimum number of operations required to convert a given string into a palindrome. * * </pre> * * @author kingdz * */ public class Algo10 { public static void main(String[] args) { String input = "aba"; int ret = getMinChange(input); System.out.println("min change:" + ret); } private static int getMinChange(String input) { int count = 0; int length = input.length(); // 将两侧的字符依次比较,以较小的字符为准,如果a和c比较,将c变成a即可,只需要改变2次 for (int i = 0; i < length / 2; i++) { char a = input.charAt(i); char b = input.charAt(length - i - 1); count = count + Math.abs((int) a - (int) b); } return count; } }
转载请注明原文地址: https://www.6miu.com/read-37771.html

最新回复(0)