请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
提示:
- 0 <= s 的长度 <= 10000
思路
直接提交return s.replace(" ", "%20")
, 常用方法信手拈来可不是每个人都能做到的(笑
我的思路是首先定义一个length, 然后遍历字符串s的每个字符, 遇见空格时length+3. 之后定义一个length长度的char数组, 将字符串s中的每个字符填入数组, 若遇见空格则填充%20
Leetcode官方解法是直接定义一个s.length * 3
长度的字符串, 之后将每个字符填入并使用size记录填入的个数. 在返回时返回的是new String(chars, 0, size)
. 代码简洁美观, 比我的好多了qwq
代码实现
我的思路:
class Solution {
public String replaceSpace(String s) {
if (s.length() == 0 || s == null) {
return s;
}
int length = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
length +=2;
}
length++;
}
char[] chars = new char[length];
int former = s.length() - 1;
int current = length - 1;
while(current >= 0) {
if (s.charAt(former) == ' ') {
chars[current--] = '0';
chars[current--] = '2';
chars[current] = '%';
} else {
chars[current] = s.charAt(former);
}
current--;
former--;
}
return new String(chars);
}
}
Leetcode解法:
class Solution {
public String replaceSpace(String s) {
int length = s.length();
char[] chars = new char[length * 3];
int size = 0;
for(int i = 0; i < length; i++) {
char c = s.charAt(i);
if(c == ' ') {
chars[size++] = '%';
chars[size++] = '2';
chars[size++] = '0';
} else {
chars[size++] = c;
}
}
return new String(chars, 0, size);
}
}
标签:Offer,++,chars,05,lcof,current,int,length,size
From: https://www.cnblogs.com/ahci316/p/17663909.html