博客
关于我
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/

你可能感兴趣的文章
Nmap扫描教程之Nmap基础知识
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
Node JS: < 一> 初识Node JS
查看>>
Node-RED中使用JSON数据建立web网站
查看>>
Node-RED中使用node-red-browser-utils节点实现选择Windows操作系统中的文件并实现图片预览
查看>>