字典序最小的字串旋轉


讓我們考慮給定的一個字串,我們知道字串是一系列字元。字典序旋轉是字串的旋轉,將其中的字元轉化為字典序。

解決方案很簡單,我們只需將給定的字串與其本身連線起來,然後在另一個數組中儲存字串的所有旋轉。之後按升序對陣列進行排序,最低值就是最終結果。

輸入和輸出

Input:
The String “BCAAFAABCD”
Output:
Rotated String: “AABCDBCAAF”

演算法

minStrRotation(str)

輸入−給定的字串。

輸出− 所需的最小字串旋轉。

Begin
   n := length of str
   define strArr to store all rotations
   tempStr := concatenate str with str again

   for i := 0 to n, do
      strArr[i] := substring of tempStr from (i to n)
   done

   sort the strArr
   return strArr[0]
End

示例

#include <iostream>
#include <algorithm>
using namespace std;

string minStrRotation(string str) {
   int n = str.size();
   string strArray[n];    //array to store all rotations of str
   string tempStr = str + str;    //concatinate str two times

   for (int i = 0; i < n; i++)
      strArray[i] = tempStr.substr(i, n);    //get sub string from ith index to nth index
   sort(strArray, strArray+n);
   return strArray[0];    //The first index is the result
}

int main() {
   string str;
   cout << "Enter String: "; cin >> str;
   cout << "Rotated String: " << minStrRotation(str);
}

輸出

Enter String: BCAAFAABCD
Rotated String: AABCDBCAAF

更新日期:17-6 月-2020

544 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告