MST

星途 面试题库

面试题:Go语言实现字符串的复杂替换操作

在Go语言中,假设有一个字符串s1 = "I like {fruit}, {fruit} is delicious.",要求使用字符串处理函数,将 {fruit} 替换为 "apple",但替换操作要考虑如果有多层嵌套花括号(如 { { {fruit} } })也能正确替换,写出具体实现代码,并说明使用的字符串处理函数及思路。
41.7万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
    "fmt"
    "strings"
)

func replaceNestedBraces(s1, target, replacement string) string {
    for {
        start := strings.Index(s1, target)
        if start == -1 {
            break
        }
        // 找到嵌套的结束位置
        end := start + len(target)
        depth := 1
        for ; end < len(s1); end++ {
            if s1[end] == '{' {
                depth++
            } else if s1[end] == '}' {
                depth--
                if depth == 0 {
                    break
                }
            }
        }
        if depth == 0 {
            newPart := s1[:start] + replacement + s1[end+1:]
            s1 = newPart
        }
    }
    return s1
}

代码使用示例

func main() {
    s1 := "I like {fruit}, { { {fruit} } } is delicious."
    target := "{fruit}"
    replacement := "apple"
    result := replaceNestedBraces(s1, target, replacement)
    fmt.Println(result)
}

使用的字符串处理函数及思路

  1. strings.Index:用于查找目标子字符串 target 在字符串 s1 中的起始位置。如果找不到,返回 -1。
  2. 遍历查找嵌套结束位置:找到起始位置后,通过遍历字符串,使用一个变量 depth 记录花括号的嵌套深度,找到匹配的结束花括号位置,确保替换的是完整的嵌套部分。
  3. 字符串拼接替换:根据找到的起始和结束位置,将原字符串分成三部分,中间替换为目标字符串,再拼接起来,更新原字符串 s1
  4. 循环替换:使用 for 循环不断查找并替换,直到字符串中不再存在目标子字符串为止。最终返回替换后的字符串。