简单的文本编辑器挑战
simple text editor challenge
在尝试解决来自 HackerRank Simple Text Editor
挑战时,我的解决方案只通过了 15 个测试用例中的 3 个。由于我无法访问测试用例,因此无法弄清楚我的代码到底出了什么问题。
我解决问题的方法如下——
- 使用向量来保存编辑器的不同状态。
- 如果我们要附加到
init
字符串(请参考下面的代码),请在 vector 的后面推送它的新状态。[OP_APPEND] - 在删除操作的情况下,将
init
字符串的新状态也推送到矢量的后面。[OP_DELETE] - 由于
init
字符串的状态存储在向量的背面,因此在发生多个 UNDO 事件的情况下,应使init
字符串与向量背面同步。[OP_PRINT & OP_UNDO]
下面是我的实现——
#include <iostream>
#include <vector>
#include <string>
#define MAX_LEN 1000000
#define MAX_TIMES 100000
using namespace std;
/* Operations supported by editor */
enum EDITOR_OPS {
OP_APPEND = 1,
OP_DELETE,
OP_PRINT,
OP_UNDO
};
/*
* @brief Driver function
*/
int main(int argc, char *argv[])
{
unsigned times; /* Total number of operations */
unsigned option; /* EDITOR_OPS operations */
string init = ""; /* Initial string */
string mystr; /* Temp string */
unsigned num; /* Number used in OP_DELETE & OP_PRINT comms */
vector<string> myvect; /* To hold various states of the editor */
unsigned curr_len = 0; /* Sum of lengths of all characters entered */
cin >> times;
if (times >= 1 && times <= MAX_TIMES) {
for (auto i = 0; i < times; i++) {
cin >> option;
if (option >= 1 && option <= 4) {
if (option == OP_APPEND) {
cin >> mystr;
curr_len += mystr.length();
if (curr_len <= MAX_LEN) {
init.append(mystr);
myvect.push_back(init);
}
}
else if (option == OP_DELETE) {
cin >> num;
if (num >=1 && num <= init.length()) {
init.erase(init.length() - num);
myvect.push_back(init);
}
}
else if (option == OP_PRINT) {
cin >> num;
if (!myvect.empty())
init = myvect.back();
if (num >= 1 && num <= init.length())
cout << init.at(num - 1) << "n";
}
else if (option == OP_UNDO) {
if (!myvect.empty())
myvect.pop_back();
}
else {
cout << "We should NOT get in heren";
}
}
}
}
return 0;
}
有人可以帮我找出代码中的错误和/或我缺少的极端情况吗?
考虑一下如果撤消然后追加代码中会发生什么情况。
- 追加要求
init
包含字符串的当前值。 - 撤消只是删除最后一个操作并保留
init
原样,这意味着它与当前状态不匹配。
您需要更改上述行为之一。
我怀疑当您进行测试时,您总是在一个或多个撤消操作后进行打印。
相关文章:
- 我无法在Visual Studio代码中使用CIN输入答案,它说输入您的年龄,但它说只读文本编辑器如何解决这个问题?
- "未定义对'WinMain@16'的引用"gcc 编辑器中的错误
- 如何从C++而不是虚幻编辑器中添加静态网格体组件的值?
- UE4 - Visual Studio在我从编辑器添加新的c ++文件后无法打开任何源文件 - UBT_COMPILED
- 图标编辑器中的自定义颜色 (VS 2015)
- Qt的QFontMetrics::horizontalAdvance()缺少代码编辑器实现
- 如何在文本编辑器中处理 [-Wc++11-extensions]
- C++链接编辑器找不到函数声明(未定义的引用)
- 如何将按钮添加到节点的属性编辑器面板,该面板调用该节点内的方法?
- QT创建者(4.2.2)编辑器中的独特指针导航
- 带有cmake的qtCreator,编辑器中未正确解析__cplusplus值
- 检查重叠时,虚幻编辑器会崩溃
- 如何在Windows中将使用Qt制作的记事本设置为默认文本编辑器
- 尝试在自定义 QT 创建器文本编辑器中创建查找和替换循环.我似乎无法设置光标位置
- UTF-16LE 编码问题与 Qt 文本编辑器用 C++ 编写
- Qt无法手动连接到任何插槽(UI编辑器)
- 编辑器(VS2019)拒绝了示例中的getline(stream,string)
- Qt委托编辑器弹出,没有父级
- 如果要调用多个成员函数,对象编辑器是否是一种好方法?
- 简单的文本编辑器挑战