字典序最小字串旋轉
讓我們思考一個字串型別,我們知道,字串是字元序列。字典序旋轉就是字串旋轉,按字典序轉換字元。
解法很簡單,我們簡單地將給定的字串本身進行串聯,然後再在一個數組中,儲存字串的所有旋轉情況。然後按升序對這個陣列進行排序,最小的值就是最終結果。
輸入輸出
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP