剑指Offer-替换空格

75 阅读1分钟

题目

请实现一个函数,把字符串中的每个空格替换成"%20"。

数据范围 0≤0≤ 输入字符串的长度 ≤1000≤1000。 注意输出字符串的长度可能大于 10001000。

样例 输入:"We are happy."

输出:"We%20are%20happy."

解析

方法一:直接模拟即可,从头到尾遍历string,遇到' '结果加上'%20'; 其他情况就直接加。
方法二:Python、GO直接有replace函数,直接使用即可(C++不大熟悉不知道有没有)。

代码

C++

class Solution {
public:
    string replaceSpaces(string &str) {
        string res;
        for (auto x: str) {
            if (x == ' ') 
                res += "%20";
            else
                res += x;
        }
        return res;
    }
};

Python

class Solution(object):
    def replaceSpaces(self, s):
        """
        :type s: str
        :rtype: str
        """
        ans = ""
        for c in s:
            if c == ' ':
                ans += "%20"
            else:
                ans += c
        return ans
class Solution(object):
    def replaceSpaces(self, s):
        """
        :type s: str
        :rtype: str
        """
        return s.replace(" ", "%20")
        

GO

func replaceSpaces(str string) string {
    replacedRune := []rune("")
    replacedSlice := []rune("%20")
    
    for _, runeValue := range str {
        if string(runeValue) == " " {
            replacedRune = append(replacedRune, replacedSlice...)
        } else {
            replacedRune = append(replacedRune, runeValue)
        }
    }
    
    return string(replacedRune)
}
func replaceSpaces(str string) string {
    return strings.Replace(str, " ", "%20", -1)
}
func replaceSpaces(str string) string {
    ans := ""
    for _, v := range str {
        if v == ' ' {
            ans += "%20"
        } else {
            ans += string(v)
        }
    }
    return ans
}