LeetCode 0844.比较含退格的字符串【Go】

简介: LeetCode 0844.比较含退格的字符串【Go】

比较含退格的字符串

LeetCode844. 比较含退格的字符串

题目描述

给定st两个字符串,当它们分别被输入到空白的文本编辑器后,如果两者相等,返回 true# 代表退格字符。

注意:如果对空文本输入退格字符,文本继续为空。

示例 1:

输入:s = "ab#c", t = "ad#c"
输出:true
解释:s 和 t 都会变成 "ac"。

示例 2:

输入:s = "ab##", t = "c#d#"
输出:true
解释:s 和 t 都会变成 ""。

示例 3:

输入:s = "a#c", t = "b"
输出:false
解释:s 会变成 "c",但 t 仍然是 "b"。

思路

题目要求:

  • 输入两个含退格的字符串,比较是否相等
  • 相等输出true,反之输出false

退格就是移除前面的一个字符,考虑使用双指针法。当快指针发现#,慢指针退一个,否则,慢指针移动。

注意

slowIndex0时,不能回退,会索引越界产生编译错误。

代码

Go

func backspaceCompare(s string, t string) bool {
  sNew := getString(s)
  tNew := getString(t)
  if sNew == tNew {
    return true
  } else {
    return false
  }
}
func getString(s string) string {
  tempArray := []string{}
  for _, item := range s {
    tempArray = append(tempArray, string(item))
  }
  slowIndex := 0
  for fastIndex := 0; fastIndex < len(tempArray); fastIndex++ {
    if s[fastIndex] != '#' {
      tempArray[slowIndex] = tempArray[fastIndex]
      slowIndex += 1
    } else if slowIndex != 0 {
      slowIndex -= 1
    }
  }
  if slowIndex == 0 {
    return ""
  }
  var result string
  for i := 0; i < slowIndex; i++ {
    result += tempArray[i]
  }
  return result
}

Link

GitHub

目录
相关文章
|
4月前
|
存储 Go 索引
go语言中遍历字符串
go语言中遍历字符串
84 5
|
3月前
|
Go
go语言for 遍历字符串
go语言for 遍历字符串
45 8
|
4月前
|
Go 索引
go语言遍历字符串
go语言遍历字符串
61 3
|
5月前
|
JavaScript
力扣3333.找到初始输入字符串Ⅱ
【10月更文挑战第9天】力扣3333.找到初始输入字符串Ⅱ
54 1
|
5月前
|
C++
Leetcode第43题(字符串相乘)
本篇介绍了一种用C++实现的字符串表示的非负整数相乘的方法,通过逆向编号字符串,将乘法运算转化为二维数组的累加过程,最后处理进位并转换为字符串结果,解决了两个大数相乘的问题。
44 9
|
6月前
|
Go
Go字节数组与字符串相互转换
Go字节数组与字符串相互转换
72 3
|
5月前
|
算法 C++
Leetcode第八题(字符串转换整数(atoi))
这篇文章介绍了LeetCode上第8题“字符串转换整数(atoi)”的解题思路和C++的实现方法,包括处理前导空格、正负号、连续数字字符以及整数溢出的情况。
43 0
|
5月前
【LeetCode 22】459.重复的子字符串
【LeetCode 22】459.重复的子字符串
51 0
|
5月前
【LeetCode 20】151.反转字符串里的单词
【LeetCode 20】151.反转字符串里的单词
38 0
|
5月前
【LeetCode 19】541.反转字符串II
【LeetCode 19】541.反转字符串II
34 0

热门文章

最新文章