简单的文本编辑器挑战

simple text editor challenge

本文关键字:编辑器 挑战 文本编辑 文本 简单      更新时间:2023-10-16

在尝试解决来自 HackerRank Simple Text Editor挑战时,我的解决方案只通过了 15 个测试用例中的 3 个。由于我无法访问测试用例,因此无法弄清楚我的代码到底出了什么问题。

我解决问题的方法如下——

  1. 使用向量来保存编辑器的不同状态。
  2. 如果我们要附加到 init 字符串(请参考下面的代码),请在 vector 的后面推送它的新状态。[OP_APPEND]
  3. 在删除操作的情况下,将init字符串的新状态也推送到矢量的后面。[OP_DELETE]
  4. 由于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原样,这意味着它与当前状态不匹配。

您需要更改上述行为之一。

我怀疑当您进行测试时,您总是在一个或多个撤消操作后进行打印。