给出 n 个字符串,全部任意组合在一起可以生产n!个字符串,长度为n个字符串的长度和
一个字符串的权值等于把这个字符串循环左移 i次后得到的字符串仍和原字符串全等的数量,i的取值为[1,字符串长度]。
求这些字符串最后生成的 n! 个字符串中权值为 K 的有多少个。
注:定义把一个串循环左移 1 次等价于把这个串的第一个字符移动到最后一个字符的后面。
输入描述:
第一行为两个正整数 n, K , n 的大小不超过 8 , K 不超过 200。
接下来有 n 行,每行一个长度不超过 20 且仅包含大写字母的字符串。
输出描述:输出一个整数代表权值为 K 的字符串数量。
输入例子:
3 2
AB
RAAB
RA
输出例子:
3
public class Main{
private static int res=0;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
String[] strs = new String[n];
for (int i = 0; i < n; i++){
strs[i] = sc.next();
}
sc.close();
Permutation(strs,0,k);//将字符串的全排列存入list
System.out.println(res);
}
private static void Permutation(String[] strs,int start,int k){
if (start == strs.length){
StringBuffer sb=new StringBuffer();
for (int i = 0; i < strs.length; i++){
sb.append(strs[i]);
}
int len=sb.length();
String s=sb.toString();
sb.append(s);
int count = 0;
for (int j = 1; j <= len; j++) {
if (sb.substring(j, j + len).equals(s)){
count++;
}
}
if (count == k){
res++;
}
}else{
for(int i=start;i<strs.length;i++) {
swap(strs,start,i);
Permutation(strs,start+1,k);
swap(strs,start,i);
}
}
}
private static void swap(String[] strs, int s, int i){
String temp = strs[s];
strs[s] = strs[i];
strs[i] = temp;
}
}