LeetCode每日一题:比较含退格的字符串(No.844)

栏目: 编程工具 · 发布时间: 6年前

给定 S 和 T 两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果。
# 代表退格字符。
复制代码

示例:

输入:S = "ab#c", T = "ad#c"
输出:true
解释:S 和 T 都会变成 “ac”。

输入:S = "ab##", T = "c#d#"
输出:true
解释:S 和 T 都会变成 “”。

输入:S = "a##c", T = "#a#c"
输出:true
解释:S 和 T 都会变成 “c”。

输入:S = "a#c", T = "b"
输出:false
解释:S 会变成 “c”,但 T 仍然是 “b”。
复制代码

思考:

循环遍历字符串字符,用一个StringBuilder来存原字符串中字母字符。
如果字符为“#”且StringBuilder长度大于0,则删除StringBuilder中末尾字符,遍历结束返回StringBuilder。
最终比较两个字符串返回值是否相同。
复制代码

实现:

class Solution {
public boolean backspaceCompare(String S, String T) {
    return function(S).equals(function(T));
}
 public String function(String s) {
        StringBuilder sb = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (c != '#') {
                sb.append(c);
            }
            else {
                if (sb.length() > 0)
                    sb.deleteCharAt(sb.length() - 1);
            }
        }
        return sb.toString();
    }
}复制代码

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Producing Masculinity

Producing Masculinity

Michele White / Routledge / 2019-3 / $39.95

Thoughtful, witty, and illuminating, in this book Michele White explores the ways normative masculinity is associated with computers and the Internet and is a commonly enacted online gender practice. ......一起来看看 《Producing Masculinity》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具