LintCode 1784: Decrease To Be Palindrome

编程入门 行业动态 更新时间:2024-10-22 23:38:50

<a href=https://www.elefans.com/category/jswz/34/1756616.html style=LintCode 1784: Decrease To Be Palindrome"/>

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;}
};

更多推荐

LintCode 1784: Decrease To Be Palindrome

本文发布于:2024-03-23 14:41:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1739380.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:LintCode   Palindrome   Decrease

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!