📣 黑五网一特惠|VIP一年通行证5折,蓝莓、Offer多多同步特惠
查看: 4469| 回复: 6
跳转到指定楼层
上一主题 下一主题
收起左侧

[题目讨论] [Google] Design Text Editor

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
Original question is here: https://www.careercup.com/question?id=5726975948226560

This is my implementation using StringBuilder with a cursor index instead of LinkedList.  The key point is: use java enum as much as possible and don't use String directly.  Using String directly is not a good OOP.  As for OOP/OOD, think about how to encapsulate the code, and reuse the code.  In TextEditor implemention, it uses the same implementation for undos and normal insert, delete, move cursor.

Java enum is as powerful as a class (in fact, enum is a class).  In the code, it demonstrates 2 ways to use java enum:
  • abstract method can be used in enum
  • A method can be overriden in enum


Using enum has the following benefits
  • passing different enums to a method,  the method can behavior differently (Strategy pattern).
  • reduce the usage of if-else or case statement, which in turn reduces the code complexity (see here for explanation).


The below implementation is a little over-engineered, but it demonstrates how OOP/OOD is supposed to be.

public class TextEditor {
    private final StringBuilder text;
    // store undo edits.
    private final Stack<UndoEdit> undoEdits;
    private int cursorIndex;

    public TextEditor() {
        this.text = new StringBuilder();
        undoEdits = new Stack<>();
        cursorIndex = 0;
    }

    public boolean moveCursorLeft() {
        return moveCursorLeft(Undo.SAVE);
    }

    private boolean moveCursorLeft(final Undo undo) {
        if (cursorIndex == 0) {
            return false;
        }

        cursorIndex--;
        undo.add(new UndoEdit(UndoEdit.Operation.MOVE_CURSOR_RIGHT), this);
        return true;
    }

    public boolean moveCursorRight() {
        return moveCursorRight(Undo.SAVE);
    }

    private boolean moveCursorRight(final Undo undo) {
        if (cursorIndex == text.length()) {
            return false;
        }

        cursorIndex++;
        undo.add(new UndoEdit(UndoEdit.Operation.MOVE_CURSOR_LEFT), this);
        return true;
    }

    public boolean insertCharacter(final char ch) {
        return insertCharacter(ch, Undo.SAVE);
    }

    private boolean insertCharacter(final char ch, final Undo undo) {
        text.insert(cursorIndex, ch);
        cursorIndex++;
        undo.add(new UndoEdit(UndoEdit.Operation.BACKSPACE), this);
        return true;
    }

    public boolean backspace() {
        return backspace(Undo.SAVE);
    }

    private boolean backspace(final Undo undo) {
        if (cursorIndex == 0) {
            return false;
        }

        cursorIndex--;
        final char ch = text.charAt(cursorIndex);
        undo.add(new UndoEdit(UndoEdit.Operation.INSERT_CHARACTER, ch), this);
        text.deleteCharAt(cursorIndex);
        return true;
    }

    public boolean undo() {
        if (!undoEdits.empty()) {
            final UndoEdit edit = undoEdits.pop();
            return edit.apply(this);
        }
        return false;
    }

    private void saveForUndo(final UndoEdit action) {
        undoEdits.add(action);
    }

    // for unit test/debug
    int cursor() {
        return cursorIndex;
    }

    @Override
    public String toString() {
        return new StringBuilder(text).insert(cursorIndex, "|").toString();
    }

    enum Undo {
        SAVE {
            @Override
            public void add(final UndoEdit edit, final TextEditor textEditor) {
                textEditor.saveForUndo(edit);
            }
        },
        UNSAVE;

        /**
         * Default implementation for doing nothing
         *
         * @param edit
         * @param textEditor
         */
        public void add(final UndoEdit edit, final TextEditor textEditor) {
            // do nothing
        }
    }

    /**
     * Helper class to encapsulate undo operation and character.
     */
    private static class UndoEdit {
        private static final char EMPTY_CHAR = '\0';
        private final Operation operation;
        private final char ch;

        public UndoEdit(final Operation operation) {
            this.operation = operation;
            this.ch = EMPTY_CHAR;
        }

        public UndoEdit(final Operation operation, final char ch) {
            this.operation = operation;
            this.ch = ch;
        }

        public boolean apply(final TextEditor editor) {
            return operation.apply(ch, editor);
        }

        @Override
        public String toString() {
            return operation.toString() + " " + ch;
        }

        enum Operation {
            MOVE_CURSOR_LEFT {
                @Override
                public boolean apply(final char ch, final TextEditor editor) {
                    return editor.moveCursorLeft(Undo.UNSAVE);
                }
            },
            MOVE_CURSOR_RIGHT {
                @Override
                public boolean apply(final char ch, final TextEditor editor) {
                    return editor.moveCursorRight(Undo.UNSAVE);
                }
            },
            INSERT_CHARACTER {
                @Override
                public boolean apply(final char ch, final TextEditor editor) {
                    return editor.insertCharacter(ch, Undo.UNSAVE);
                }
            },
            BACKSPACE {
                @Override
                public boolean apply(final char ch, final TextEditor editor) {
                    return editor.backspace(Undo.UNSAVE);
                }
            };

            public abstract boolean apply(char ch, TextEditor editor);
        }
    }
}


评分

参与人数 2大米 +15 收起 理由
jaychsu + 5 很有用的信息!
14417335 + 10 很有用的信息!

查看全部评分


上一篇:分布式存储系统学习资料
下一篇:如何设计分布式系统

本帖被以下淘专辑推荐:

🔗
daifei4321 2019-2-20 07:51:28 | 只看该作者
全局:
好像原题有要求“All functions above should take O(1) time. ”
代码里的text.insert和text.deleteCharAt会不会有问题呢……

评分

参与人数 2大米 +4 收起 理由
zli_test + 3 good point!
14417335 + 1 good question

查看全部评分

回复

使用道具 举报

🔗
 楼主| zli_test 2019-2-21 07:47:16 | 只看该作者
全局:
daifei4321 发表于 2019-2-19 15:51
好像原题有要求“All functions above should take O(1) time. ”
代码里的text.insert和text.deleteCharA ...

I will change StringBuilder to a Doubly LinkedList
回复

使用道具 举报

🔗
 楼主| zli_test 2019-2-21 13:12:07 | 只看该作者
全局:
daifei4321 发表于 2019-2-19 15:51
好像原题有要求“All functions above should take O(1) time. ”
代码里的text.insert和text.deleteCharA ...

StringBuilder's deleteChar and insertChar have linear time complexity.  Here is the new code to use doubly linkedlist.  Since it is well encapsulated, it is easy to switch to a different implementation:
  1. public class TextEditor {
  2.     private static final char EMPTY_CHAR = '\0';
  3.     private final ListNode head;
  4.     private final ListNode tail;
  5.     // store undo edits.
  6.     private final Stack<UndoEdit> undoEdits;
  7.     private ListNode cursor;

  8.     public TextEditor() {
  9.         head = new ListNode();
  10.         tail = new ListNode();
  11.         head.next = tail;
  12.         tail.prev = head;
  13.         undoEdits = new Stack<>();
  14.         cursor = tail;
  15.     }

  16.     public boolean moveCursorLeft() {
  17.         return moveCursorLeft(Undo.SAVE);
  18.     }

  19.     private boolean moveCursorLeft(final Undo undo) {
  20.         if (cursor.prev == head) {
  21.             return false;
  22.         }

  23.         cursor = cursor.prev;
  24.         undo.add(new UndoEdit(UndoEdit.Operation.MOVE_CURSOR_RIGHT), this);
  25.         return true;
  26.     }

  27.     public boolean moveCursorRight() {
  28.         return moveCursorRight(Undo.SAVE);
  29.     }

  30.     private boolean moveCursorRight(final Undo undo) {
  31.         if (cursor.next == null) {
  32.             return false;
  33.         }

  34.         cursor = cursor.next;
  35.         undo.add(new UndoEdit(UndoEdit.Operation.MOVE_CURSOR_LEFT), this);
  36.         return true;
  37.     }

  38.     public boolean insertCharacter(final char ch) {
  39.         return insertCharacter(ch, Undo.SAVE);
  40.     }

  41.     private boolean insertCharacter(final char ch, final Undo undo) {

  42.         final ListNode node = new ListNode(ch);
  43.         node.prev = cursor.prev;
  44.         node.next = cursor;
  45.         cursor.prev.next = node;
  46.         cursor.prev = node;

  47.         undo.add(new UndoEdit(UndoEdit.Operation.BACKSPACE), this);
  48.         return true;
  49.     }

  50.     public boolean backspace() {
  51.         return backspace(Undo.SAVE);
  52.     }

  53.     private boolean backspace(final Undo undo) {
  54.         if (cursor.prev == head) {
  55.             return false;
  56.         }
  57.         final char ch = cursor.prev.ch;
  58.         undo.add(new UndoEdit(UndoEdit.Operation.INSERT_CHARACTER, ch), this);

  59.         final ListNode deleted = cursor.prev;
  60.         deleted.prev.next = cursor;
  61.         cursor.prev = deleted.prev;
  62.         deleted.prev = null;
  63.         deleted.next = null;
  64.         return true;
  65.     }

  66.     public boolean undo() {
  67.         if (!undoEdits.empty()) {
  68.             final UndoEdit edit = undoEdits.pop();
  69.             return edit.apply(this);
  70.         }
  71.         return false;
  72.     }

  73.     private void saveForUndo(final UndoEdit action) {
  74.         undoEdits.add(action);
  75.     }

  76.     // for unit test/debug
  77.     ListNode cursor() {
  78.         return cursor;
  79.     }

  80.     @Override
  81.     public String toString() {
  82.         final StringBuilder builder = new StringBuilder();
  83.         ListNode node = head.next;
  84.         while (node != null) {
  85.             if (node == cursor) {
  86.                 builder.append("|");
  87.             }
  88.             if (node != tail) {
  89.                 builder.append(node.ch);
  90.             }
  91.             node = node.next;
  92.         }
  93.         return builder.toString();
  94.     }

  95.     enum Undo {
  96.         SAVE {
  97.             @Override
  98.             public void add(final UndoEdit edit, final TextEditor textEditor) {
  99.                 textEditor.saveForUndo(edit);
  100.             }
  101.         },
  102.         UNSAVE;

  103.         /**
  104.          * Default implementation for doing nothing
  105.          *
  106.          * @param edit
  107.          * @param textEditor
  108.          */
  109.         public void add(final UndoEdit edit, final TextEditor textEditor) {
  110.             // do nothing
  111.         }
  112.     }

  113.     /**
  114.      * Helper class to encapsulate undo operation and character.
  115.      */
  116.     private static class UndoEdit {

  117.         private final Operation operation;
  118.         private final char ch;

  119.         public UndoEdit(final Operation operation) {
  120.             this.operation = operation;
  121.             this.ch = EMPTY_CHAR;
  122.         }

  123.         public UndoEdit(final Operation operation, final char ch) {
  124.             this.operation = operation;
  125.             this.ch = ch;
  126.         }

  127.         public boolean apply(final TextEditor editor) {
  128.             return operation.apply(ch, editor);
  129.         }

  130.         @Override
  131.         public String toString() {
  132.             return operation.toString() + " " + ch;
  133.         }

  134.         enum Operation {
  135.             MOVE_CURSOR_LEFT {
  136.                 @Override
  137.                 public boolean apply(final char ch, final TextEditor editor) {
  138.                     return editor.moveCursorLeft(Undo.UNSAVE);
  139.                 }
  140.             },
  141.             MOVE_CURSOR_RIGHT {
  142.                 @Override
  143.                 public boolean apply(final char ch, final TextEditor editor) {
  144.                     return editor.moveCursorRight(Undo.UNSAVE);
  145.                 }
  146.             },
  147.             INSERT_CHARACTER {
  148.                 @Override
  149.                 public boolean apply(final char ch, final TextEditor editor) {
  150.                     return editor.insertCharacter(ch, Undo.UNSAVE);
  151.                 }
  152.             },
  153.             BACKSPACE {
  154.                 @Override
  155.                 public boolean apply(final char ch, final TextEditor editor) {
  156.                     return editor.backspace(Undo.UNSAVE);
  157.                 }
  158.             };

  159.             public abstract boolean apply(char ch, TextEditor editor);
  160.         }
  161.     }

  162.     static class ListNode {
  163.         char ch;
  164.         ListNode prev;
  165.         ListNode next;

  166.         ListNode() {
  167.             ch = EMPTY_CHAR;
  168.         }

  169.         ListNode(final char ch) {
  170.             this.ch = ch;
  171.         }

  172.         @Override
  173.         public boolean equals(final Object o) {
  174.             final ListNode that = (ListNode) o;
  175.             return ch == that.ch;
  176.         }
  177.     }
  178. }
复制代码



Here is the unit test:
  1. import static org.hamcrest.CoreMatchers.is;
  2. import static org.junit.Assert.assertThat;

  3. import org.junit.Before;
  4. import org.junit.Test;

  5. import TextEditor.ListNode;
  6. public class TextEditorTest {
  7.     private static final ListNode TAIL = new ListNode();
  8.     private TextEditor editor;

  9.     @Before
  10.     public void setup() {
  11.         this.editor = new TextEditor();
  12.     }
  13.     @Test
  14.     public void test() {
  15.         assertThat(editor.toString(), is("|"));
  16.         assertThat(editor.cursor(), is(TAIL));

  17.         editor.insertCharacter('a');
  18.         assertThat(editor.toString(), is("a|"));
  19.         assertThat(editor.cursor(), is(TAIL));

  20.         editor.insertCharacter('b');
  21.         assertThat(editor.toString(), is("ab|"));
  22.         assertThat(editor.cursor(), is(TAIL));

  23.         editor.insertCharacter('c');
  24.         assertThat(editor.toString(), is("abc|"));
  25.         assertThat(editor.cursor(), is(TAIL));

  26.         assertThat(editor.moveCursorRight(), is(false));
  27.         assertThat(editor.toString(), is("abc|"));
  28.         assertThat(editor.cursor(), is(TAIL));

  29.         editor.moveCursorLeft();
  30.         editor.moveCursorLeft();
  31.         assertThat(editor.moveCursorRight(), is(true));
  32.         assertThat(editor.toString(), is("ab|c"));
  33.         assertThat(editor.cursor(), is(new ListNode('c')));

  34.         assertThat(editor.moveCursorRight(), is(true));
  35.         assertThat(editor.toString(), is("abc|"));
  36.         assertThat(editor.cursor(), is(TAIL));

  37.         editor.moveCursorLeft();
  38.         assertThat(editor.toString(), is("ab|c"));
  39.         assertThat(editor.cursor(), is(new ListNode('c')));

  40.         editor.moveCursorLeft();
  41.         assertThat(editor.toString(), is("a|bc"));
  42.         assertThat(editor.cursor(), is(new ListNode('b')));

  43.         editor.backspace();
  44.         assertThat(editor.toString(), is("|bc"));
  45.         assertThat(editor.cursor(), is(new ListNode('b')));

  46.         assertThat(editor.moveCursorLeft(), is(false));
  47.         assertThat(editor.toString(), is("|bc"));
  48.         assertThat(editor.cursor(), is(new ListNode('b')));

  49.         assertThat(editor.undo(), is(true));
  50.         assertThat(editor.toString(), is("a|bc"));
  51.         assertThat(editor.cursor(), is(new ListNode('b')));

  52.         assertThat(editor.undo(), is(true));
  53.         assertThat(editor.toString(), is("ab|c"));
  54.         assertThat(editor.cursor(), is(new ListNode('c')));

  55.         assertThat(editor.undo(), is(true));
  56.         assertThat(editor.toString(), is("abc|"));
  57.         assertThat(editor.cursor(), is(TAIL));

  58.         assertThat(editor.undo(), is(true));
  59.         assertThat(editor.toString(), is("ab|c"));
  60.         assertThat(editor.cursor(), is(new ListNode('c')));

  61.         assertThat(editor.undo(), is(true));
  62.         assertThat(editor.undo(), is(true));
  63.         assertThat(editor.toString(), is("ab|c"));
  64.         assertThat(editor.cursor(), is(new ListNode('c')));

  65.         assertThat(editor.undo(), is(true));
  66.         assertThat(editor.toString(), is("abc|"));
  67.         assertThat(editor.cursor(), is(TAIL));

  68.         assertThat(editor.undo(), is(true));
  69.         assertThat(editor.toString(), is("ab|"));
  70.         assertThat(editor.cursor(), is(TAIL));

  71.         assertThat(editor.undo(), is(true));
  72.         assertThat(editor.toString(), is("a|"));
  73.         assertThat(editor.cursor(), is(TAIL));
  74.     }
  75. }
复制代码


评分

参与人数 1大米 +5 收起 理由
14417335 + 5 给你点个赞!

查看全部评分

回复

使用道具 举报

🔗
gtonyoogle 2019-2-24 00:33:48 | 只看该作者
全局:
很有用的信息!
回复

使用道具 举报

🔗
geeti 2019-2-24 09:10:38 | 只看该作者
全局:
这算是系统还是算法?
回复

使用道具 举报

🔗
yuqinlear 2019-2-25 05:38:33 | 只看该作者
全局:
请问这道题是不是用线段树最优?但是线段树实现确实太烦碎了啊。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表