- Decrease To Be Palindrome
Given a string s with a-z. We want to change s into a palindrome with following operations:
- change ‘z’ to ‘y’;
- change ‘y’ to ‘x’;
- change ‘x’ to ‘w’;
… - change ‘c’ to ‘b’;
- 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:
- Change ‘c’ to ‘b’: “abb”
- 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;
}
};
本文介绍了一种算法,用于计算将任意给定的由小写字母组成的字符串转换为回文串所需的最少操作次数。操作包括将字符按字母顺序递减替换。通过对比字符串首尾字符并逐步内缩,该算法高效地计算出了所需的操作总数。





