Scale AI OA 面试真题解析:RichText Formatting 富文本格式合并

16次阅读
没有评论

RichText Formatting

When displaying text at Scale, we want to be able to store and display richtext: text that has formatting like bold, italic, etc. For this interview, we will only consider the formatting options of bold and italic.

The way that we store richtext will be as a JSON array of objects that represent text segments with formatting options. The definitions for this JSON type is:

type RichTextSegment = {
  text: string;
  bold: boolean;
  italic: boolean;
}

type RichText = RichTextSegment[];

Part 1: Validate and Fix

Our richtext format should follow the following rule: any two consecutive segments of text in the RichText object should not have redundant segments. Segments are redundant if they have the same formatting combination of bold and italic.

Implement a function fix(richtext) that takes invalid constructed richtext objects that have redundantly formatted segments and converts them into valid richtext objects by concatenating the text of those segments together. For example, the invalid text above is converted into the valid text above.

fix(invalidText: RichText) -> validText: RichText

Examples:

  • invalidText = [
  • {"bold": true, "italic": false, "text": "One two "},
  • {"bold": true, "italic": false, "text": "three four"},
  • ]

Valid result:

[{"bold": true, "italic": false, "text": "One two three four"}
]

这道题考察的是富文本段落合并:输入是一个由多个文本片段组成的数组,每个片段都有 <code>bold</code> 和 <code>italic</code> 两个布尔标记。题目要求把相邻且格式完全相同的片段合并成一个片段,也就是把它们的文本直接拼接起来,同时保留原有格式不变。实现时只需要线性遍历数组,维护当前结果的最后一个片段;如果下一个片段和它格式一致,就追加文本,否则就新建一个片段。核心是字符串拼接与按格式分组,时间复杂度通常是 O(n)。

正文完
 0