J - Just a Magic String
J - Just a Magic String
Time Limit: 1000/1000MS (Java/Others) Memory Limit: 131072/131072KB (Java/Others)
Description
You have such a string $S$ a
, every time you can copy $S$ to $T$ ,change a
in $T$ to b
, b
to a
, then add $T$ after $S$.
For example,
a
ab
abba
abbabaab
abbabaabbaababba
......
Finally you will get a infinite magic string.
Now, given a string $X$ only containing a
and b
, you should tell me if it appears in the magic string?
If it appears, than output the location it first appears, otherwise, output -1
;
Input
A line with a string that consists only a
and b
and no more than $10^6$ characters.
Output
Print the position of the first occurrence of the string, or -1
if it doesn't exist.
Sample input
bab
Sample output
3
Sample input
baab
Sample output
5
Sample input
aaabbb
Sample output
-1
总结
想了半天不知道怎么做,结果还是楚枫说的kmp算法来解决的
#include<iostream> #include<string> #include<vector> using namespace std; int kmp_find(const string& target,const string& pattern) { const int target_length = target.size(); const int pattern_length = pattern.size(); int * overlay_value = new int[pattern_length]; overlay_value[0] = -1; int index = 0; for(int i=1;i<pattern_length;++i) { index = overlay_value[i-1]; while(index>=0 && pattern[index+1]!=pattern[i]) { index = overlay_value[index]; } if(pattern[index+1]==pattern[i]) { overlay_value[i] = index +1; } else { overlay_value[i] = -1; } } //match algorithm start int pattern_index = 0; int target_index = 0; while(pattern_index<pattern_length&&target_index<target_length) { if(target[target_index]==pattern[pattern_index]) { ++target_index; ++pattern_index; } else if(pattern_index==0) { ++target_index; } else { pattern_index = overlay_value[pattern_index-1]+1; } } if(pattern_index==pattern_length) { return target_index-pattern_index; } else { return -2; } delete [] overlay_value; } int main() { string source="a"; string a=source; string pattern; int n=25; cin >>pattern; for(int i=1;i<=n;i++){ a=source; for(int j=0;j<a.length();j++){ if(a[j]=='a') a[j]='b'; else a[j]='a'; } source+=a; } cout<<kmp_find(source,pattern)+1<<endl; return 0; }