最强解析面试题:替换空格「建议收藏!」

文章目录

  • 最强解析面试题:替换空格「建议收藏!」
    • 题目
      • 示例1
      • 思路
      • 1、strings.Replace(str,” “,”%20”,-1)
        • 代码
      • 2、Replace 思路
        • 代码
    • Replace 源码
    • 附录

最强解析面试题:替换空格「建议收藏!」_第1张图片

最强解析面试题:替换空格「建议收藏!」

文章讲解 “ 替换空格 ” 经典面试题,包含思路及源码,及解惑!

题目

请实现一个函数,将一个字符串s中的每个空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

数据范围:
0<=len(s)<=1000。保证字符串中的字符为大写英文字母、小写英文字母和空格中的一种。

示例1

输入:
“We Are Happy”
返回值:
“We%20Are%20Happy”

思路

1、strings.Replace(str,” “,”%20”,-1)

代码

package main

import (
    "fmt"
    "strings"
)

func main () {
     
    param := "We Are Happy"
    fmt.Println("hello https://tool.lu/",strings.Replace(param," ","%20",-1))
}

2、Replace 思路

  • 通过遍历得出替换后的长度,并构建新对象
  • 使用双指针为新对象赋值,指针区间为 “ 无需替换内容 ”
  • 期间伴随着 Slice 的切割操作

代码

package main

import (
    "fmt"
    "strings"
)

func main () {
     
    p := "We Are Happy"
    fmt.Println("hello https://tool.lu/",Replace(p," ","%20"))
}
func Replace(s, old, ne string) string {
     
   s1 := s
   n := 0
   for {
     
      i := strings.Index(s1, old)
      if i == -1 {
     
         break
      }
      n++
      s1 = s1[i+len(old):]
   }

   if n <= 0 {
     
      return s
   }
   var b strings.Builder
   b.Grow(len(s) + n*(len(ne)-len(old)))
   start := 0
   for i := 0; i < n; i++ {
     
      j := start
      j += strings.Index(s[start:], old)
      b.WriteString(s[start:j])
      b.WriteString(ne)
      start = j + len(old)
   }
   b.WriteString(s[start:])
   return b.String()
}

Replace 源码

// Replace returns a copy of the string s with the first n
// non-overlapping instances of old replaced by new.
// If old is empty, it matches at the beginning of the string
// and after each UTF-8 sequence, yielding up to k+1 replacements
// for a k-rune string.
// If n < 0, there is no limit on the number of replacements.
func Replace(s, old, new string, n int) string {
     
 if old == new || n == 0 {
     
  return s // avoid allocation
 }

 // Compute number of replacements.
 if m := Count(s, old); m == 0 {
     
  return s // avoid allocation
 } else if n < 0 || m < n {
     
  n = m
 }

 // Apply replacements to buffer.
 var b Builder
 b.Grow(len(s) + n*(len(new)-len(old)))
 start := 0
 for i := 0; i < n; i++ {
     
  j := start
  if len(old) == 0 {
     
   if i > 0 {
     
    _, wid := utf8.DecodeRuneInString(s[start:])
    j += wid
   }
  } else {
     
   j += Index(s[start:], old)
  }
  b.WriteString(s[start:j])
  b.WriteString(new)
  start = j + len(old)
 }
 b.WriteString(s[start:])
 return b.String()
}

附录

忙碌和早起

你可能感兴趣的:(服务端,golang,替换空格,剑指Offer,面试,编程算法题)