请实现一个函数,把字符串 s
中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy." 输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
方法一:字符串内置方法
使用 replace()
方法。
时间复杂度
方法二:遍历替换
我们直接遍历字符串,遇到空格就替换成 %20
即可。
时间复杂度
class Solution:
def replaceSpace(self, s: str) -> str:
return s.replace(' ', '%20')
class Solution:
def replaceSpace(self, s: str) -> str:
ans = []
for c in s:
ans.append('%20' if c == ' ' else c)
return ''.join(ans)
class Solution {
public String replaceSpace(String s) {
return s.replaceAll(" ", "%20");
}
}
class Solution {
public String replaceSpace(String s) {
StringBuilder ans = new StringBuilder();
for (char c : s.toCharArray()) {
ans.append(c == ' ' ? "%20" : c);
}
return ans.toString();
}
}
class Solution {
public:
string replaceSpace(string s) {
string ans;
for (char ch : s) {
if (ch == ' ')
ans += "%20";
else
ans += ch;
}
return ans;
}
};
func replaceSpace(s string) string {
return strings.Replace(s, " ", "%20", -1)
}
func replaceSpace(s string) string {
ans := strings.Builder{}
for _, c := range s {
if c == ' ' {
ans.WriteString("%20")
} else {
ans.WriteRune(c)
}
}
return ans.String()
}
/**
* @param {string} s
* @return {string}
*/
var replaceSpace = function (s) {
return s.split(' ').join('%20');
};
/**
* @param {string} s
* @return {string}
*/
var replaceSpace = function (s) {
return s.replace(/\s/g, '%20');
};
/**
* @param {string} s
* @return {string}
*/
var replaceSpace = function (s) {
const ans = [];
for (const c of s) {
ans.push(c === ' ' ? '%20' : c);
}
return ans.join('');
};
function replaceSpace(s: string): string {
return s.replace(/\s/g, '%20');
}
function replaceSpace(s: string): string {
const strArr = [];
for (const c of s) {
strArr.push(c === ' ' ? '%20' : c);
}
return strArr.join('');
}
impl Solution {
pub fn replace_space(s: String) -> String {
s.replace(' ', "%20")
}
}
impl Solution {
pub fn replace_space(s: String) -> String {
let mut result = String::new();
for c in s.chars() {
if c == ' ' {
result.push_str("%20");
} else {
result.push(c);
}
}
result
}
}
public class Solution {
public string ReplaceSpace(string s) {
return s.Replace(" ", "%20");
}
}
public class Solution {
public string ReplaceSpace(string s) {
StringBuilder res = new StringBuilder();
foreach (var c in s) {
if (c == ' ') {
res.Append("%20");
} else {
res.Append(c);
}
}
return res.ToString();
}
}
class Solution {
/**
* @param String $s
* @return String
*/
function replaceSpace($s) {
$rs = '';
for ($i = 0; $i < strlen($s); $i++) {
if ($s[$i] === ' ') {
$rs = $rs . '%20';
} else {
$rs = $rs . $s[$i];
}
}
return $rs;
}
}