某大厂的笔试题,解压压缩的字母串

2023-05-16

这几天看到一个大厂的面试题,感觉比较有意思,是学习递归的好题目,下面和大家分享一下这道题的解法。

题目说明:

压缩的字母规则是,连续相同的字母串压缩成:连续的个数 +[字母串]。如 aaa,压缩成:3[a];amamam 压缩成 3[am]。

请实现解压缩字符串功能。实现程序语言不限制。完成时间两个小时,过程不能看手机,不能切屏。

自测样例,输入:3[k] 2[am] 预期输出:kkkamam

输入:2[k3[am]] 预期输出:kamamamkamamam

解题思路:

这个题目初看,解压缩的算法不难设计,只需要进行简单的递归就可以了,这里就不再赘述,而不用递归而且保证算法在o(n)时间内完成倒是有些难度。

这里需要用到栈的思想处理,倒序完成。

1.初始态中将输入字符串赋值给结果

2.找到最后一个[符号,取出其前面的数字以及与这个[最近的]符号,之间的所有字符,将这些字符串按照数字的个数展开,并用展开后的字符串对于数字[字符串]的原结构进行替换,保存到结果当中。

3处理完所有[即可完成解压。

代码如下:

import re
def UnFoldString(repeat,strInput):
    if repeat<1:
        return None
    result=""
    for i in range(0,repeat):
        result=result+strInput
    return result

def UnCompressString(strInput):
    pat = r'\d+'
    result=strInput
    numlist = re.findall(pat, strInput)#把所有数字通过re匹配出来,这个做法只适用于Python,后续可以优化
    numIndex= len(numlist)-1#记录目前展开的位置
    for j in range(0,len(result)):#遍历一次复杂度o(n)
        i= len(result)-1-j#关键在于使用栈的方式,从后找到最后一个[
        if result[i]=='[':
            numlen=len(numlist[numIndex])
            #print(numlen,i,numlist[numIndex],result[i-numlen:i])
            if result[i-numlen:i]!=numlist[numIndex]:#如果最后一个[前面不是最后一个数字,肯定是有问题的
                return None
            else:
                compressStr=result[i+1:].split(']')[0]#当前位置i对应的是[,那么从i+1到下一个]一定是要解压的字符,通过split方式最直观
                comressStrLen=len(compressStr)+2
                result=result[:i-numlen]+UnFoldString(int(numlist[numIndex]),compressStr)+result[i+comressStrLen:]
                numIndex=numIndex-1
    return result
strInput="3[k]2[am]"
print(UnCompressString(strInput))
strInput="2[k3[am]]"
print(UnCompressString(strInput))
strInput="12[k3[am]]"
print(UnCompressString(strInput))

发散题目:

当然这题做到这肯定没结束,如果在面试中出现这道题目,我肯定会问对于压缩算法的实现策略,也就是把输入输出调转过来。

输入:kamamamkamamam 预期输出: 2[k3[am]]

这个想递归实现的方式都不简单。

可以先考虑下基本思路,因为这个结果需要嵌套,也就是左子串,右子串和中间你已经找到的最长子串都需要进行递归。

其中找最长的子串可以考虑贪心算法,直接按照字符串一半长度逐步尝试。

然后逐步向右移位。把左、右半边不在最长子串中的序列递归压缩。

具体代码及注释如下:

def FindMaxsubstring(strInput):
    #print(strInput)
    strlen=len(strInput)
    if strlen<2:
        return 0,strInput,strlen
    repeat=1
    subStr=""
    if strlen==2:
        if strInput[0]==strInput[1]:
            return 2,strInput[0],strlen
        else:
          return 0,strInput,strlen
    for i in range(0,int(strlen/2)):
        greedyIndex=int(strlen/2)-i
        if greedyIndex<1:
            break
        repeatMax=int(strlen/greedyIndex)
        j=2
        while strInput[:greedyIndex]==strInput[greedyIndex*(j-1):greedyIndex*j]:
            j=j+1
            repeat=repeat+1
            subStr=strInput[:greedyIndex]
            strlen=greedyIndex
        if repeat>1:
            return repeat,subStr,greedyIndex*repeat
    return 0, strInput, strlen
def GenResult(strInput):
    repeat,lastRepeat=0,0
    subStr,lastSubStr="",""
    lastLen=0
    leftIndex=0
    strLen=len(strInput)
    rightIndex=strLen
    if strLen<2:
        return strInput
    for i in range(0,strLen-1):
        lastRepeat,lastSubStr,lastRightIndex=FindMaxsubstring(strInput[i:])
        if lastRepeat>1 and len(lastSubStr)>lastLen:
            #print(lastSubStr,str(i))
            repeat=lastRepeat
            lastLen = len(lastSubStr)
            subStr=lastSubStr#递归生成子串
            rightIndex=lastRightIndex
            leftIndex=i
    if repeat <2:
        return strInput
    if leftIndex<2 and (strLen-rightIndex)<2:

        return strInput[:leftIndex]+str(repeat)+"["+GenResult(subStr)+"]"+strInput[rightIndex+leftIndex:]
    else:

        return GenResult(strInput[:leftIndex]) + str(repeat) + "[" + GenResult(subStr) + "]" + GenResult(strInput[rightIndex+leftIndex:])

print(GenResult("kkkamam"))
print(GenResult("kamamamkamamam"))


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

某大厂的笔试题,解压压缩的字母串 的相关文章

  • 点击<a href="#"/>后屏幕滚动问题

    问 xff1a 当 lt a href 61 34 34 gt 点击后屏幕会滚动到最上面 xff0c 有啥办法不让屏幕滚动 xff1f 答 xff1a href 61 34 javascript void 0 34 或 nclick 61
  • 内存管理知识

    原创作品 xff0c 允许转载 xff0c 转载时请务必以超链接形式标明文章 原始出处 作者信息和本声明 否则将追究法律责任 http xqtesting blog 51cto com 4626073 808548 一般的程序语言 xff0
  • 用户体验:别让我想,别让我停!

    http xqtesting blog 51cto com 4626073 813561 在交互设计中 xff0c 存在着几条普遍的法则令网页设计更有效 最重要的一条是 别让我思考 xff0c 越简洁越好 比如不要因为奇怪的表达方式强迫用户
  • MySQL慢查询的两种分析方案 slow sql

    http blog csdn net ylqmf article details 6541542 前一段日子 xff0c 我曾经设置了一次记录在MySQL数据库中对慢于1秒钟的SQL语句进行查询 想起来有几个十分设置的方法 xff0c 有几
  • 如何使用SQL Profiler 性能分析器

    http blog csdn net ylqmf article details 6541625 ysql 的 sql 性能分析器主要用途是显示 sql 执行的整个过程中各项资源的使用情况 分析器可以更好的展示出不良 SQL 的性能问题所在
  • magento中生成https链接的简单方法

    有关magento中https的基础知识 xff0c 请看 magento中的启用https 如果是在项目的后期才决定采用https xff0c 那么就要面临一个问题 xff1a 大量的生成url的代码需要修改 xff0c 这是一个很大的工
  • 树莓派无屏幕连接WiFi

    将刷好 Raspbian 系统的 SD 卡用电脑读取 在 boot 分区 xff0c 也就是树莓派的 boot 目录下新建 wpa supplicant conf 文件 xff0c 按照下面的参考格式填入内容并保存 wpa supplica
  • MySQL数据库存储引擎MyISAM和InnoDB的对比详解

    http www mysqlops com 2011 12 09 myisam E5 92 8Cinnodb E5 AF B9 E6 AF 94 E8 AF A6 E8 A7 A3 html 之前Eugene兄已经写过两篇关于myisam转
  • 为什么magento的rewrite方法对抽象类无效

    magento中 xff0c 是没法通过Mage getModel 34 xx xx 34 配合xml中的 lt rewrite gt 实现abstruct class的rewrite 为什么 xff1f 这需要详细了解一下magento中
  • magento中在.htaccess设置website code

    在 htaccess中 xff0c 添加以下的内容 xff1a SetEnvIf Host www newjueqi com MAGE RUN CODE 61 newjueqi SetEnvIf Host www newjueqi com
  • apache两种工作模式详解

    http blog chinaunix net space php uid 61 20541969 amp do 61 blog amp id 61 351485 刚接触这两个配置时很迷糊 xff0c 全部开启或全部注释没有几多变化 今天搜
  • Apache处理http请求的生命周期

    Apache请求处理循环详解 Apache请求处理循环的11个阶段都做了哪些事情呢 xff1f 1 Post Read Request阶段 在正常请求处理流程中 xff0c 这是模块可以插入钩子的第一个阶段 对于那些想很早进入处理请求的模块
  • 提高MySQL插入记录的速度

    http hi baidu com jackbillow blog item 65ea47248f645521d50742e7 html 在myisam engine下 1 尽量使用insert into table name values
  • 最常用的http状态码

    200 OK 找到了该资源 xff0c 并且一切正常 202 Accepted 服务器已接受请求 xff0c 但尚未处理 amp bsp 301 Moved Permanently 被请求的资源已永久移动到新位置 302 Found 请求的
  • shell中通过ftp批量上传文件

    为了在shell中上传文件 xff0c 需要避免在控制台中通过交互的方式输入ftp的登录密码 xff0c 这时要安装一个强大的ftp命令行工具 xff1a lftp xff0c 通过lftp登录ftp服务器的格式如下 xff1a lftp
  • 你可能不了解的strtotime函数

    出处 xff1a http www phppan com 2011 06 php strtotime 作者 xff1a 胖胖 在前面的文章中 xff0c 我们提到strtotime函数在使用strtotime 1 month 求上一个月的今
  • PHP的词法解析器:re2c

    出处 xff1a http www phppan com 2011 09 php lexical re2c 作者 xff1a 胖胖 re2c是一个扫描器制作工具 xff0c 可以创建非常快速灵活的扫描器 它可以产生高效代码 xff0c 基于
  • 由浅入深探究mysql索引结构原理、性能分析与优化

    出处 xff1a http www phpben com post 61 74 摘要 xff1a 第一部分 xff1a 基础知识 第二部分 xff1a MYISAM 和 INNODB 索引结构 1 简单介绍 B tree B 43 tree
  • php的strtotime函数源码分析

    最近想实现一个多语言版的strtotime函数 xff0c 所以阅读了php源码中strtotime函数的实现 xff0c 很感谢 胖胖 大大的文章 xff08 http www phppan com 2011 06 php strtoti

随机推荐