73. SQL代码补全功能 | 豆包MarsCode AI刷题

140 阅读2分钟

本题所使用的编程语言:Python

题目复现

问题描述

在开发SQL编辑器时,实现自动补全功能是提高用户体验的重要一环。小C需要实现一个功能,根据用户输入的字符片段,快速从已知的SQL关键字和数据库相关名称中找到所有以该片段开头的候选词,并按字典序输出。

例如,当用户输入 s 时,编辑器需要自动提示以 s 开头的所有可能选项,如 select。如果用户输入 fr,则需要提示 fromfrom_mobile。如果在提示中只有一个选项符合,如输入 from_ 时只提示 from_mobile


测试样例

样例1:

输入:num = 8,data = ["select", "from", "where", "limit", "origin_log_db", "event_log_table", "user_id", "from_mobile"], input = "f"
输出:'from,from_mobile'

样例2:

输入:num = 8,data = ["select", "from", "where", "limit", "origin_log_db", "event_log_table", "user_id", "from_mobile"], input = "wh"
输出:'where'

样例3:

输入:num = 8,data = ["select", "from", "where", "limit", "origin_log_db", "event_log_table", "user_id", "from_mobile"], input = "z"
输出:'-1'

样例4:

输入:num = 8,data = ["select", "from", "where", "limit", "origin_log_db", "event_log_table", "user_id", "from_mobile"], input = "origin"
输出:'origin_log_db'

相关知识点分析

1、关于python的正则表达式 对于正则表达式,我们使用简单的语言来总结:使用一套规则来完成对于文字的匹配,但是对于正则表达式来说其规则大有不同,而对于本题我们所需要使用到的正则表达式的匹配模式如下:

image.png 而使用上方的模式进行对于文章的处理之后,我们就可以使用对应的匹配方法同时辅以对应的模式,如果符合对应的条件则为通过,反之则为不通过

思路分析

在了解了对于正则表达式相关的方法的书写和完善,那么我们就可以通过遍历对于每一个字符进行匹配,如果符合相关输入,则为正确匹配,反之为不正确的匹配,而通过这里并予以统计和返回就可以达到题目所想要的效果

代码实现

import re
def solution(num, data, input):
    # Please write your code here
    pattern=re.compile('^'+input)
    stra = []
    for i in data:
        if re.match(pattern,i)!=None and i not in stra:
          stra.append(i)
        else:
            continue
    if not stra:
     return '-1'
    stra.sort()
    result = ','.join(stra) #这里是将对应的结果进行结合处理
    return result
    
if __name__ == "__main__":
    #  You can add more test cases here
    testData1 = ["select", "from", "where", "limit", "origin_log_db", "event_log_table", "user_id", "from_mobile"]
    testData2 = ["select", "from", "where", "limit", "group", "having", "in", "index", "inner", "insert", "like", "log_db", "log_table", "user_id", "group_name", "group_id"]

    print(solution(8, testData1, "f") == "from,from_mobile" )
    print(solution(16, testData2, "g") == "group,group_name,group_id")
    print(solution(16, testData2, "m") == "-1")

运行结果和提交截图

image.png

image.png