登录
首页 >  Golang >  Go问答

如何在 Golang Strings.Builder 中删除最后一个字符?

来源:stackoverflow

时间:2024-03-16 08:51:31 252浏览 收藏

在 Go 语言中使用 `strings.Builder` 时,无法直接删除最后一个字符。替代方法是创建最终字符串,然后对其进行切片以删除最后一个字符,或者在添加最后一个字符之前检查是否到达终点。此外,通过使用 `net.IP` 和 `func net.IPv4(...) IP`,可以轻松格式化 IP 地址。对于经典的回溯问题,例如生成有效 IP 地址,可以采用分而治之的方法,将问题分解为子问题并递归求解,在发现无效路径时尽早停止探索。

问题内容

我试图将一个字节写入 golang strings.builder 对象,调用一个函数,然后删除最后添加的字节。但我找不到一种方法来修剪通过引用传递的 strings.builder 对象中的最后一个字节。

func iPAdrressHelper(s string, steps int, sb *strings.Builder, result *[]string) {
// lots of code
    sb.WriteByte(s[i])
    sb.WriteByte('.')
    iPAdrressHelper(s[i+1:], steps, sb, result)
    // The following function is not available
    sb.DeleteByte('.')
//other code
}

解决方案


无法从 strings.builder 对象中“删除”字符。

可以做的是通过调用 sb.string() 创建最终字符串,然后对结果进行切片以删除最后一个字符:

str := sb.string()
if len(str) > 0 {
  str = str[:len(str)-1]
}

或者您可以简单地不添加最后的“。”首先通过检测您是否到达终点。

顺便说一句,您似乎只是想格式化 ip 地址?如果是这种情况,请检查 type net.IPfunction func net.IPv4(...) IP。您可以轻松执行以下操作:

str := net.ipv4(10,0,0,1).string()

作为第二个旁注,递归代码感觉“被迫”。在我看来,一个简单的循环不仅可能更加高效,而且更具可读性。

编辑:根据您的评论,这似乎是一个“面试问题”。评论中的链接供其他感兴趣的人使用。

问题:给定一个字符串 s,通过添加三个点返回所有可能的有效 ip。

这是一个经典的回溯问题。你可以把它想象成一棵必须探索的树,一旦一条路径被证明会导致无效结果,你就可以尽早停止。这棵树就是“点的位置”的树。

作为一般方法,以下是解决这些问题的方法。

当“问题得到解决”时,您创建一个具有基本情况的递归,并使用该解决方案返回一个单例单例是一个只有一个元素的集合,在本例中是有效的解决方案。在某些问题中,检查解决方案是否无效并返回空集合可能会有所帮助。在这里,没有必要。

如果问题“未解决”,则生成每个“下一个部分解决方案”,并针对“剩余问题”递归调用该函数,并合并它们的结果。您最终返回组合结果的集合。

类似这样的事情:

func recursivehelper(s string, parts []string) []string {
  if len(s) == 0 {
    // base case, problem solved.
    // we assume that if we ever get to
    // this point, the solution is valid.
    return strings.join(parts, ".") 
  }
  // we're not at the end, so let's explore
  // the tree, collect the results and
  // return then
  var res []string

  // each candidate solution must consume
  // 1 to 3 characters from the string, 
  // which must be a valid number between
  // 0 and 255, with no leading zeroes. 
  // say you have a function that generates
  // those candidates (exercise: write it). 
  // you could also inline that code
  // here instead, if it's simple enough and
  // you're short on time. 
  for _, c := range gencandidates(s, parts) {
    res = append(res, recursivehelper(s[len(c):], append(parts, c))...)
  }
  return res
}

它起作用的原因是,如果您正在探索的树的部分没有生成任何候选者,它将返回一个空切片。这完全停止了对树分支的探索——回溯。当您将空切片附加到当前正在构建的解决方案集中时,它不会更改当前的解决方案集,因此您永远不会在结果切片中出现“垃圾”。最后,由于只有在调用是有效候选结果的情况下才会使用空字符串调用辅助函数,因此对基本情况的最终调用必须产生有效的解决方案。

更一般地说,如果您看到一个具有更复杂状态的更复杂的回溯问题,您可以定义一个具有一些辅助函数的 state 类型:

type state struct {...}
func (s state) next() []state {
  // return a slice of potential
  // candidate states
}
func (s state) invalid() bool {
  // true if this (partial or not) state
  // is already provably invalid
}
func (s state) valid() bool {
  // true if this is valid.
  // valid means it solves the problem.
  // note that this is not the same as
  // !s.invalid(). it's like you got 3 kinds of
  // states: you know for sure it's valid, 
  // you know for sure it's invalid (and won't ever be made valid), or
  // it may be able to produce valid children. 
}

您甚至可以将 state 定义为更“通用”回溯算法的接口。这样,您就可以解决任何回溯问题:

func backtrack(st state, fn func(state)) {
  if st.valid() {
    // found a solution, yield it
    fn(st)
  }
  // find child states
  for _, c := range st.next() {
    if c.invalid() {
      // quickly discard this entire branch
      continue
    }
    // continue exploring the tree
    backtrack(c, fn)
  } 
}

您可以像这样从主解决方案函数中调用它,假设您填写了状态代码以使用 ip 地址等:

initialstate := state{...} 
var ips []string
backtrack(initialstate, func (sol state) {
  // you'll need a function that transforms
  // a solution state into the ip address
  // it represents
  ip := sol.string()
  ips = append(ips, ip)
})
return ips

仅此而已!

一种方法可能是获取字符串,重置构建器并再次写入。

buf := sb.String()
buf = strings.TrimSuffix(buf, ".")
sb.Reset()
sb.WriteString(buf)

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>