给你一个字符串s,问不断地把首字母取下来放到最后,一共能形成多少个不同的字符串。
这道题其实挺简单的,只需要不停遍历就好,一共可以生成s长度的字符串,再遍历进行比较即可。
那我把它单独写一下是因为这道题除了用最笨的办法之外,还可以练习set容器的使用以及string的取子串函数(substr())
- set:集合,关联容器的一种,基于红黑树的平衡二叉检索树的数据结构。功能就像它的名字一样,它里面的元素具有互异性,所以具有自动去重功能,即不会重复插入相同键值的元素,而采取忽略处理。所以我们只需要将新生成的字符串插入到set容器中,最后set容器大小,即为不同字符串的个数。
set<T> name; //T为元素类型, name为变量名
//如:
set<string> st;
st.insert(p) //插入元素,插入过程中,自动去重。
st.erase(p) //删除元素
st.size() //set容器内元素的数量
- substr(pos, len)
pos为开始位置, len为子串长度
注意:
如果pos 超过了字符串的大小,就抛出一个out_of_range异常;
但如果是pos + len 超过了字符串的大小,那么substr()会只拷贝到字符串的末尾。在下面题解中,你会见到这种用法。
题解代码:
时间复杂度:O(N)
#include <bits\stdc++.h>
#define ll long long
#define ld long double
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
string s;
while(cin >> s) {
set<string> st;
st.insert(s);
int len = s.length();
for(int i = 1; i < len; ++ i) {
string t = s.substr(i, len) + s.substr(0, i);
st.insert(t);
}
cout << st.size() << endl;
}
return 0;
}