华为机器机试-九宫格按键输入法
题目介绍
■ 题目描述
九宫格按键输入,判断输出,有英文和数字两个模式,默认是数字模式,数字模式直接输出数字,英文模式连续按同一个按键会依次出现这个按键上的字母,如果输入”/”或者其他字符,则循环中断。
要求输入一串按键,输出屏幕显示。
输入描述:
输入范围为数字 0~9 和字符’#’、’/’,输出屏幕显示,例如,
在数字模式下,输入 1234,显示 1234
在英文模式下,输入 1234,显示,adg
输出描述:
- #用于切换模式,默认是数字模式,执行#后切换为英文模式;
- /表示延迟,例如在英文模式下,输入 22/222,显示为 bc;
- 英文模式下,多次按同一键,例如输入 22222,显示为 b;
示例 1 输入输出示例仅供调试,后台判题数据一般不包含示例
输入
123#222235/56
输出
123adjjm
解题思路
这个题目思路很简单,题目要求怎么做代码就怎么写好了。
先捋一捋题目,输入一串字符串,输出一串字符串,对于输入的字符串做如下处理,使用#
切换模式,当是数字模式时,按1
输出1
,当是英文模式时,根据按的数字的次数来轮次选择格子上的某个字母,比如说2
对应的是abc
按一次输出a
,按两次输出b
,次数多了就从头继续轮。如果想输出aa
的话就需要在两个2
中间插入/
,变成2/2
就可以输出了。
分情况讨论嘛
1,遇到#
就切换模式
2,/
表示延迟
3,在英文模式中对数字进行处理,当在英文模式下遍历到某个数字的时候,要看一下有多少同样的数字,然后再根据这个数量去对应的字符串中找。
代码实现
cpp代码
#include <limits.h>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string minWindow(string s) {
string res;
int flagsysteam = 0;
map<char, string> hashmap;
hashmap['0'] = " ";
hashmap['1'] = ",.";
hashmap['2'] = "abc";
hashmap['3'] = "def";
hashmap['4'] = "ghi";
hashmap['5'] = "jkl";
hashmap['6'] = "mno";
hashmap['7'] = "pqrs";
hashmap['8'] = "tuv";
hashmap['9'] = "wxyz";
for (int i = 0; i < s.size(); i++) {
if (s[i] <= '9' && s[i] >= '0') {
if (flagsysteam == 0) {
res.push_back(s[i]);
continue;
}
if (flagsysteam == 1) {
int r = i;
char Key = s[i];
string tempstr = hashmap[Key];
while (r < s.size() && s[r] == s[i]) r++;
int index =
(r - i - 1) %
(tempstr.size()); //长度为r - i因为字符串里是0起步需要再-1
res.push_back(tempstr[index]);
i = r - 1; //将i 移动到r因为continue后会自动++,所以先-1
continue;
}
}
if (s[i] == '#') {
flagsysteam = (flagsysteam + 1) % 2;
continue;
}
if (s[i] == '/') {
continue;
}
}
return res;
}
};
int main() {
Solution a;
string test;
cin >> test;
cout << a.minWindow(test) << endl;
return 0;
}