A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.
You are given a string s, consisting of lowercase English letters and a positive integer k. Your task is to reorder the letters in the string sin such a way that the resulting string is a k-string.
The first input line contains integer k (1 ≤ k ≤ 1000). The second line contains s, all characters in s are lowercase English letters. The string length s satisfies the inequality 1 ≤ |s| ≤ 1000, where |s| is the length of string s.
Rearrange the letters in string s in such a way that the result is a k-string. Print the result on a single output line. If there are multiple solutions, print any of them.
If the solution doesn't exist, print "-1" (without quotes).
2 aazz
azaz
3 abcabcabz
-1
ps:感谢莫莫的解题报告
这个题目主要是需要理解题意,静下心来看下,其实很简单。
题意:
题目给一个K,给定一个字符串,里面包含若干字母。如果字符串可以用里面所有的字母重新组合为K-string,输出重组以后的字符串,否则输出-1。K-string即为一个字符串可以分为一个子串复制K倍然后得到字符串。
解题思路:
先判断是不是K-string,用一个数组保存从a~z出现的次数。如果某一个次数不是K的倍数,那么便直接输出-1即可。否则则将里面的次数全部除以K,用来输出。
#include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<string> #include<algorithm> #include<map> using namespace std; char a[1004],c[1004]; //a是输入的字符串,c则是需要连续输出K倍的子串 int b[26]; //保存a~z字母出现额次数 int main() { int i,j,k; while(cin>>k) { memset(b,0,sizeof(b)); cin>>a; for(i=0;i<strlen(a);i++) b[a[i]-'a']++; int flag=0; for(i=0;i<26;i++) if(b[i]%k!=0) //不满足次数是K的倍数,跳出,输出-1 { flag=1; break; } if(flag) cout<<"-1"<<endl; else { int ll=-1; for(i=0;i<26;i++) if(b[i]) { int x=b[i]/k; //次数除以K for(j=0;j<x;j++) c[++ll]=i+'a'; //用c来保存需要输出的子串 } c[++ll]='\0'; for(i=0;i<k;i++) //输出重组以后的K-string cout<<c; cout<<endl; } } return 0; }