题目描述:
请实现一个函数,将一个字符串s中的每个空格替换成“%20”。
例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
解题思路:
定义一个string,然后遍历字符串s,遇到为空格的字符则将其替换
代码:
public String replaceSpace(String s) {
// write code here
String result = "";
for (int i = 0; i < s.length(); i++) { // 字符串的长度是length()
if (s.charAt(i) == ' ') { // 比较一个字符是不是空格,要注意这里的引号为单引号
result = result + s.charAt(i);
} else {
result = result + "%20";
}
}
return result;
}
结论:
- 复杂度
空间复杂度:O(n)
时间复杂度:O(n) - 知识点
关于字符串的操作函数常用的有:length(),charAt();toLowerCase(),toUpperCase(),congcat(),contains(),equals(),isEmpty(),split();
要注意字符与字符串的引号区别