博客
关于我
LeetCode0844. 比较含退格的字符串
阅读量:304 次
发布时间:2019-03-03

本文共 690 字,大约阅读时间需要 2 分钟。

一. 题目

判断两个字符串是否是同一个回文串,但字符串中可以包含特殊字符'#',特殊字符'#'的作用是可以清空前面的所有字符。例如,字符串"ab#c"可以转换为"ab",而"abc#def"则会转换为"def"。

示例:

- 字符串S = "abc#def" - 字符串T = "abc#def" - 结果应该是True,因为两个字符串在去除'#'后的结果相同。
二. 方法一: 无脑暴力法

通过逐个遍历两个字符串中的每个字符,分别构建两个结果字符串。遇到'#'时,截断当前结果字符串的最后一个字符。如果遇到其他字符,则直接追加到结果字符串中。最后比较两个结果字符串是否相同。

解题代码:

```pythondef backspaceCompare(self, S: str, T: str) -> bool: str1 = "" str2 = "" for ele in S: if ele != "#": str1 += ele else: str1 = str1[:-1] for ele in T: if ele != "#": str2 += ele else: str2 = str2[:-1] return str1 == str2```

分析:

- 该方法通过两次遍历字符串,分别处理每个字符,时间复杂度为O(n),其中n是字符串的长度。 - 在遇到'#'时,截断字符串的最后一个字符,这一步操作的时间复杂度为O(k),其中k是截断前的字符数量。因此,在最坏情况下,时间复杂度可能会接近O(n^2)。 - 该方法简单易懂,但在处理大量特殊字符时可能会导致性能问题。

转载地址:http://ysum.baihongyu.com/

你可能感兴趣的文章
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错TypeError: this.getOptions is not a function
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>
npm错误Error: Cannot find module ‘postcss-loader‘
查看>>
npm,yarn,cnpm 的区别
查看>>
NPOI
查看>>