题目来源
题目描述
题目解析
这道题考察阅读理解。
问:什么时候需要输出?
- 如果是数字模式下直接输出
- 如果是英文模式,那么当当前输入和之前输入的字符不同时需要输出
- 因此需要记忆上一次输入了什么以及输入了多少次
- 当当前输入和之前输入不同时:
- 先输出之前的字符
- 如果之前字符是2,那么直接输出a
- 如果之前字符是22,那么直接输出b
- 如果之前字符是222,那么直接输出c
- 如果之前字符是2222,那么直接输出a
- 如果之前字符是22222,那么直接输出b
- 然后看当前字符是不是最后一个字符,如果是,直接输出
- 先输出之前的字符
- 如果切换了模式,那么可能需要输出(因为可能会有##)
问:/
是什么意思?
- 中文模式无意义
- 英文模式下
- 比如22/222
- 当输入第一个2时,记录: prevCh = 2, count = 1
- 当输入第二个2时,记录: prevCh = 2,count=2
- 当输入
/
时,发现当前的/和之前的2不同,那么:- 将之前的"22"输出,它可以转换为b
- 同时将count重置为0
- 当输入第三个2时,记录: prevCh = 2, count = 1
- 当输入第四个2时,记录: prevCh = 2, count = 2
- 当输入第五个2时,记录: prevCh = 2, count = 3。
- 同时发现这是最后一个2,因此它"222"转为c输出
- 比如22/222
#include <utility>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
class Solution {
private:
char prevCh;//上一次的数字按键,实际上只是一个字符
int count = 0;
std::string outstr;
std::vector<std::string> strings{" ", ",.", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
void showSceen(char &str){
int strIdx = str - '0';
if(strIdx == 0){
outstr.append(strings[0]);
}else{
int strLen = strings[strIdx].length(); //数字上的字符长度
int index = count % strLen == 0 ? strLen - 1 : count % strLen - 1;
outstr.append(1, strings[strIdx][index]);
}
}
public:
void process(std::string str){
bool isEn = false;
for (int i = 0; i < str.size(); ++i) {
char currCh = str[i];
if(currCh == '#'){ // 中英文切换
isEn = !isEn;
if(count != 0){//temp有值,说明有字符需要输出
showSceen(prevCh);
prevCh = ' ';
count = 0;
}
continue;
}
if(isEn){
/*
* 英文输入
*/
if(count == 0){ // 之前没有按键
if(currCh == '/'){
continue;
}
prevCh = currCh;
count = 1;
}else if(prevCh != currCh){ //按键数字发生变化,需要输出字符
showSceen(prevCh); // 把之前的字符所表示意思输出来
if(i == str.size() - 1){ // 最后一个字符了
showSceen(currCh);
break;
}
if(currCh == '/'){
count = 0;
}else{
prevCh = currCh;
count = 1;
}
}else{
count++;
if(i == str.size() - 1){
showSceen(currCh);
}
}
}else{
/*
* 数字输入
*/
if(currCh == '/'){ //数字中的/没有意义
continue;
}
outstr.append(1, currCh); //数字直接输出
}
}
std::cout <<outstr <<"\n";
}
};
int main()
{
// string input;
// getline(cin, input);
Solution solu;
solu.process("1#22/222");
return 0;
}