Problem E : Password Search
From:UVA, 902
Being able to send encoded messages during World War II was very important to the Allies. The messages were always sent after being encoded with a known password. Having a fixed password was of course insecure, thus there was a need to change it frequently. However, a mechanism was necessary to send the new password. One of the mathematicians working in the cryptographic team had a clever idea that was to send the password hidden within the message itself. The interesting point was that the receiver of the message only had to know the size of the password and then search for the password within the received text.
A password with size N can be found by searching the text for the most frequent substring with N characters. After finding the password, all the substrings that coincide with the password are removed from the encoded text. Now, the password can be used to decode the message.
To illustrate your task, consider the following example in which the password size is three (N=3) and the text message is just baababacb. The password would then be aba because this is the substring with size 3 that appears most often in the whole text (it appears twice) while the other six different substrings appear only once (baa ; aab ; bab ; bac ; acb).
The input file contains several test cases, each of them consists of one line with the size of the password, 0 < N ≤ 10, followed by the text representing the encoded message. To simplify things, you can assume that the text only includes lower case letters.
For each test case, your program should print as output a line with the password string.
3 baababacb
aba
初读题目,感觉是要用map来结题,调用iterator的指针指出来重复最多的字符串
小技巧,substra 的使用,可以直接在string里截取(a,b)的长度,a是第几个元素,b是截取的长度。
思路出来了之后写好代码好久不能ac去网上看了些其他人的代码,
6 aba2 aba 1 thequickbrownfoxjumpsoverthelazydog 3 thequickbrownfoxjumpsoverthelazydog 4 testingthecodetofindtheerrortestandtestagain 5 thearraycanbetoobigsobecarefulandtherecantberarecasescanbe 2 ababa 2 babab 1 ab 1 a当n的值大于string的长度时要注意,break;
还有就是for(int i=0;i<=str.size()-n;i++)主意是小于等于,可以写出来简单的列子,证明。下面是代码;
#include<iostream> #include<string> #include<cstring> #include<map> #include<vector> #include<algorithm> using namespace std; //////////////////////////////////// int main(){ int n; string str; map<string,int>m; //int prelen; while(cin>>n>>str){ //scanf("%s",str); int len=str.size(); if(n<=len){ string s; for(int i=0;i<=str.size()-n;i++){ s=str.substr(i,n); m[s]++; } //cout<<str<<endl; int max=-1; string ans; for(map<string,int>::const_iterator it=m.begin();it!=m.end();it++){ if(it->second>max){ max=it->second; ans=it->first; } } cout<<ans<<endl; m.clear(); } str.clear(); } return 0; }