C++程式碼查詢列印字串所需的撥號旋轉次數


假設我們有一個旋轉撥號,其中包含所有小寫英文字母。撥號連線到一個印表機,撥號指標指向的字元會在3秒鐘後打印出來。旋轉撥號最初停留在字母'a'上,並且在列印字元時不會重置到初始位置。給定一個字串s,我們需要列印該字串。每當我們將撥號移動到另一個字母時,就會發生一次旋轉。我們需要找出列印給定字串's'所需的總旋轉次數。

因此,如果輸入類似於s = "elephant",則輸出將為63。

步驟

為了解決這個問題,我們將遵循以下步驟:

t := 'a'
res := 0
for initialize i := 0, when i < size of s, update (increase i by 1),
do:
   res := res + minimum of (|t - s[i]|, 26 - |t - s[i]|)
   t := s[i]
return res

示例

讓我們看下面的實現來更好地理解:

#include <bits/stdc++.h>
using namespace std;
#define N 100
int solve(string s) {
   char t = 'a';
   int res = 0;
   for(int i = 0; i < s.size(); i++){
      res += min(abs(t - s[i]), 26 - abs(t - s[i]));
      t = s[i];
   }
   return res;
}
int main() {
   string s = "elephant";
   cout<< solve(s);
   return 0;
}

輸入

"elephant"

輸出

63

更新於:2022年3月11日

133 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.