请实现一个函数,把字符串
s
中的每个空格替换成"%20"。
?示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
?限制:
0 <= s 的长度 <= 10000
? 使用 strings 包提供的API,replace函数。
? replace源码中使用StringBuilder新建字符串,并在原字符串中寻找被替换子字符串的index,并记录已经替换完的字符串的尾位置pos(pos初始为0)。然后将pos到index之间的子字符串连接到新字符串上,再连接新字符串,并寻找下一个被替换子字符串的位置。当index=-1是说明没有需要替换的子字符串,退出循环。
/**
* Replace all occurrences of a substring within a string with another string.
* @param inString {@code String} to examine
* @param oldPattern {@code String} to replace
* @param newPattern {@code String} to insert
* @return a {@code String} with the replacements
*/
public static String replace(String inString, String oldPattern, @Nullable String newPattern) {
if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {
return inString;
}
int index = inString.indexOf(oldPattern);
if (index == -1) {
// no occurrence -> can return input as-is
return inString;
}
int capacity = inString.length();
if (newPattern.length() > oldPattern.length()) {
capacity += 16;
}
StringBuilder sb = new StringBuilder(capacity);
int pos = 0; // our position in the old string
int patLen = oldPattern.length();
while (index >= 0) {
sb.append(inString.substring(pos, index));
sb.append(newPattern);
pos = index + patLen;
index = inString.indexOf(oldPattern, pos);
}
// append any characters to the right of a match
sb.append(inString.substring(pos));
return sb.toString();
}
class Solution {
public String replaceSpace(String s) {
if(s.length()==0){
//获取字符串的长度要用length(),是个函数
//获取数组的长度要用length,是个变量
return s;
}
s=s.replace(" ","%20");
//字符串replace函数可以替换指定子字符,也可以用来删除子字符串
//字符串还有插入函数:s.insert(index,“插入字符串")
return s;
}
}
?增加一个新的字符串,并遍历原字符串。如果原字符串中的字符为空格,就将%20拼接到新字符串中,否则就拼接原字符
?时间复杂度O(n),空间复杂度O(n)
class Solution {
public String replaceSpace(String s) {
StringBuilder sb = new StringBuilder();
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
if(ch==‘ ‘){
//字符用单引号
sb.append("%20");
}
else{
sb.append(ch);
}
}
return sb.toString();
}
}
原文:https://www.cnblogs.com/simpleName/p/14613470.html