有道搜索框题解

http://poj.youdao.com/nanti1/B/

描述
在有道搜索框中,当输入一个或者多个字符时,搜索框会出现一定数量的提示,如下图所示:


现在给你N个单词和一些查询,请输出提示结果,为了简化这个问题,只需要输出以查询词为前缀的并且按字典序排列的最前面的8个单词,如果符合要求的单词一 个也没有请只输出当前查询词。
输入
第一行是一个正整数N,表示词表中有N个单词。
接下来有N行,每行都有一个单词,注意词表中的单词可能有重复,请忽略掉重复单词。所有的单词都由小写字母组成。
接下来的一行有一个正整数Q,表示接下来有Q个查询。
接下来Q行,每行有一个单词,表示一个查询词,所有的查询词也都是由小写字母组成,并且所有的单词以及查询的长度都不超过20,且都不为空
其中:N<=10000,Q<=10000
输出
对于每个查询,输出一行,按顺序输出该查询词的提示结果,用空格隔开。
样例输入
10
a
ab
hello
that
those
dict
youdao
world
your
dictionary
6
bob
d
dict
dicti
yo
z
样例输出
bob
dict dictionary
dict dictionary
dictionary
youdao your
z

#include "stdio.h" #include "set" #include "string" #include "iostream" #include "vector" using namespace std; int n; int vec_size; set <string> ss; vector <string> vec_str; inline int find_str(string s1, string s2) { int i; int j; i = s1.size(); j = s2.size(); const char * p1 = s1.c_str(); const char * p2 = s2.c_str(); if (i < j) { return -1; } int count = 0; while (count < j) { if (*(p1+count) != *(p2+count) ) { return -1; } ++ count; } return 0; } int out_put_string_with_prefix(string str) { int ret = 0; int i; int start_pos = vec_size; int stop_pos = 0; int match = 0; for (i=0; i<vec_size; i++) { if (vec_str[i].c_str()[0] == str.c_str()[0]) { if (start_pos == vec_size) { start_pos = i; } stop_pos = i; } else { if (start_pos != vec_size) { break; } } } for (i=start_pos; i<=stop_pos; i++) { if (find_str(vec_str[i], str) != -1) { if (match) { cout << " " << vec_str[i]; ++match; } else { match = 1; cout << vec_str[i]; } } if (match == 8) { break; } } if ((start_pos == vec_size) || (!match) ) { // none match cout << str.c_str() << endl; } else { cout << endl; // if match, output "endl" } } int main() { int q; char tmp21[21]; scanf("%d", &n); int i; for (i=0; i<n; i++) { scanf("%s", tmp21); string tmp_str = tmp21; ss.insert(tmp_str); } set <string>::iterator sit; for (sit=ss.begin(); sit!=ss.end(); sit++) { string tmp = (*sit); vec_str.push_back(tmp); } vec_size = vec_str.size(); scanf("%d", &q); for (i=0; i<q; i++) { scanf("%s", tmp21); string tmp_str = tmp21; out_put_string_with_prefix(tmp_str); } return 0; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值