LintCode 1784: Decrease To Be Palindrome

本文介绍了一种算法,用于计算将任意给定的由小写字母组成的字符串转换为回文串所需的最少操作次数。操作包括将字符按字母顺序递减替换。通过对比字符串首尾字符并逐步内缩,该算法高效地计算出了所需的操作总数。
  1. Decrease To Be Palindrome

Given a string s with a-z. We want to change s into a palindrome with following operations:

  1. change ‘z’ to ‘y’;
  2. change ‘y’ to ‘x’;
  3. change ‘x’ to ‘w’;
  4. change ‘c’ to ‘b’;
  5. change ‘b’ to ‘a’;
    Returns the number of operations needed to change s to a palindrome at least.

Example
Example 1:

Input: “abc”
Output: 2
Explanation:

  1. Change ‘c’ to ‘b’: “abb”
  2. Change the last ‘b’ to ‘a’: “aba”
    Example 2:

Input: “abcd”
Output: 4

解法1:
代码如下:

class Solution {
public:
    /**
     * @param s: the string s
     * @return: the number of operations at least
     */
    int numberOfOperations(string &s) {
        int n = s.size();
        if (n <= 1) return 0;
        
        int count = 0;
        int i = 0, j = n - 1;
        while(i < j) {
            if (s[i] != s[j]) count += abs(s[j] - s[i]);
            i++;
            j--;
        }
        
        return count;
    }
};
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值