在C ++中获得相同字符串所需的最小旋转
问题陈述
给定一个字符串,我们需要找到获得相同字符串所需的最小转数
示例
如果输入字符串为“bbbbb”,则至少需要旋转一圈
算法
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
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬