本文已参与「新人创作礼」活动,一起开启掘金创作之路。
原文链接:blog.csdn.net/roufoo/arti…
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;
}
};