剑指 Offer 05. 替换空格
LeetCode题目要求
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例
输入:s = "We are happy."
输出:"We%20are%20happy."
解题思路
借助一个额外 StringBuilder 空间,遍历字符数组,比较简单直接上代码吧
上代码
class Solution {
public String replaceSpace(String s) {
char[] cs = s.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cs.length; i++) {
char c = cs[i];
if (c == ' ') {
sb.append("%20");
} else {
sb.append(c);
}
}
return sb.toString();
}
}
重难点
附:学习资料链接
标签:Day8,Offer,StringBuilder,05,空格,cs,sb From: https://www.cnblogs.com/blacksonny/p/17031894.html