LintCode 1784: Decrease To Be Palindrome"/>
LintCode 1784: Decrease To Be Palindrome
- 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;}
};
更多推荐
LintCode 1784: Decrease To Be Palindrome
发布评论