UVA 902 Password Search (字符串)



Password Search

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.

Problem

Your mission has been simplified as you are only requested to write a program that, given the size of the password and the encoded message, determines the password following the strategy given above.

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).

Input

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.

Output

For each test case, your program should print as output a line with the password string.

Sample Input

3 baababacb

Sample Output

aba  
 
 
代码:
#include<iostream>
#include<string>
#include<map>

using namespace std;

string str0,ans,str1;
map <string,int> mymap;

int main(){
    int n;
    while(cin>>n){
        int maxn=-1;
        mymap.clear();
        cin>>str0;
        for(int i=0;i<=str0.length()-n;i++){
            str1=str0.substr(i,n);
            mymap[str1]++;
        }
        map<string,int>::iterator it;
        for(it=mymap.begin();it!=mymap.end();it++){
            if(it->second>maxn){
                maxn=it->second;
                ans=it->first;
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值