原题链接:剑指Offer05:替换空格
时间复杂度O(n)
,空间复杂度O(n)
Golang
package main
import "fmt"
func replaceSpace(s string) string {
var newS []byte
for i := range s {
if s[i] == ' ' {
newS = append(newS, '%', '2', '0')
} else {
newS = append(newS, s[i])
}
}
return string(newS)
}
func main() {
s := "We are happy."
res := replaceSpace(s)
fmt.Println(res)
}
Python
class Solution:
def replaceSpace(self, s: str) -> str:
return "%20".join(s.split(" "))
if __name__ == "__main__":
solution = Solution()
print(solution.replaceSpace("We are happy."))
C#
public class Solution
{
public string ReplaceSpace(string s)
{
return s.Replace(" ", "%20");
}
}
class Program
{
static void Main(string[] args)
{
Solution solution = new Solution();
Console.WriteLine(solution.ReplaceSpace("We are happy."));
}
}