用 C++ 計算相同字串的最小旋轉次數


問題陳述

給定一個字串,我們需要找到使字串相同的所需最小旋轉次數

示例

如果輸入字串為“bbbbb”,則至少需要旋轉 1 次

演算法

1. Initialize result = 0
2. Make a temporary string equals to original string concatenated with itself.
3. Take the substring of temporary string of size same as original string starting from second character i.e. index 1
4. Increment the counter
5. Check whether the substring becomes equal to original string. If yes, then break the loop. Else go to step 2 and repeat it from the next index

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int getRotationCount(string str) {
   string temp = str + str;
   int n = str.length();
   for (int i = 1; i <= n; ++i) {
      string sub = temp.substr(i, str.size());
         if (str == sub) {
            return i;
         }
   }
   return n;
}
int main() {
   string str = "bbbbb";
   cout << "Rotation count = " << getRotationCount(str) <<
   endl;
   return 0;
}

在編譯並執行上述程式時,將生成以下輸出

輸出

Rotation count = 1

更新日期: 2019-12-23

248 次瀏覽

啟動您的職業生涯

完成此課程獲得認證

開始
廣告
© . All rights reserved.