华为机试:输入法查找


#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

/* 把输入的每一行的编码解析为拼音和汉字 */
void parse_raw(string &str, string &hanzi, string &pinyin)
{
	const char *p = str.c_str();
	const char *q = p;

	while (*q != '_')
		q++;

	// note [) 范围是前开后闭
	string _hanzi(p, q);
	string _pinyin(q + 1, p + str.size());

	hanzi = _hanzi;
	pinyin = _pinyin;
}

/* 把输入的拼音解析为拼音和数字 */
void parse_input(string &str, string &pinyin, int &nums)
{
	const char *p = str.c_str();
	const char *q = p;

	while (*q != '\0' && !('0' <= *q && *q <= '9'))
		q++;

	string _pinyin(p, q);
	pinyin = _pinyin;

	if ('0' <= *q && *q <= '9')
		nums = *q - '0';
	else
		nums = 0;
}

int main()
{
	map<string, vector<string> > ssmap;
	string str_raw;

    /* 定义常量 */
	const string tag_start = "Code";
	const string tag_search = "Search";
	const string tag_end = "End";
	string hanzi, pinyin;
	int num;

	cin >> str_raw;

    /* 等于开始信号 */
	if (str_raw == tag_start)
	{
	    /* 读取编码表 */
		cin >> str_raw;
		while (str_raw != tag_search)
		{
			parse_raw(str_raw, hanzi, pinyin);
			ssmap[pinyin].push_back(hanzi);
			cin >> str_raw;
		}

        /* 输入的search */
		cin >> str_raw;

		/* 解析输入的拼音 */
		parse_input(str_raw, pinyin, num);


		cin >> str_raw;

		/* 结束标志位 */
		if (str_raw == tag_end)
		{
		    /* 判断 这个拼音是否存在*/
			if (ssmap.find(pinyin) == ssmap.end())
			{
				cout << "Erro" << endl;
			}
			else if (num > 0)
			{
			    /* 判断num是否存在 */
			    if(num < ssmap[pinyin].size())
                {
                    cout << ssmap[pinyin][num - 1] << endl;
                }
                else
                {
                    cout << "Erro" << endl;
                }

			}
			else
			{
			    /* 输出前5个 */
				size_t i = 0;

				for ( i = 0; i < ssmap[pinyin].size() - 1 && i != 4; i++)
					cout << ssmap[pinyin][i] << ";";
				cout << ssmap[pinyin][i] << endl;
			}
		}
	}

	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dmfrm

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值