Ring character: to find the minimum number of steps given string. c ++

Ring character

A ring from an alphabet consisting of end to end rings, a ring pointer initially pointing to the letters a, can be clockwise or counterclockwise rotation of each of a grid. Such as a counterclockwise rotation through z, clockwise rotation to b. Given a string now, seeking transfer requires a minimum number of times.
Here Insert Picture Description
Input line, a string; at least to the number of output revolutions.

sample input:
zeus

sample output:
18

Data range:
data points 1-2 string length than 10
data points 3-5 string length 100 or less
data points 6-10 string length 10,000 or less

Ideas:

  • Due to the number of revolutions of the output per revolution is the distance between a letter, it is possible to use the difference between the two codes asc letters to represent the distance from one letter to another letter to go through the
  • One letter to another letter, there are two possibilities, either counterclockwise in the past, either clockwise past, the shortest distance is the smaller of the two ways
  • Since the distance is positive, the absolute value is required. In the code I wrote a function of the absolute value of the conversion. Of course, since the converted asc integer calculation, it is also possible to do with the function abs.
#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
int jue(int a)
{
       if(a<0)    return -a;
       else if(a==0) return a;
       else return a;
}
char str[10011];
int main()
{
       cin>>str;
       int length=strlen(str);
       int sum=0;
       int num=0;
       for(int i=0;i<length;i++)
       {
              int temp=0;
              temp=str[i]-'a';
              sum+=min(jue(temp-num),26-jue(temp-num));
              num=temp;
       }
       cout<<sum<<endl;
       return 0;

}



Published 29 original articles · won praise 1 · views 947

Guess you like

Origin blog.csdn.net/qq_44654498/article/details/104901130