1.题目:
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
2.思路:
方法一:直接用库函数repalce;
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return string字符串
*/
public String replaceSpace (String s) {
// write code here
s=s.replace(" ","%20");
return s;
}
}方法二:由于每次替换从 1 个字符变成 3 个字符,使用字符数组可方便地进行替换。建立字符数组地长度为 s 的长度的 3 倍,这样可保证字符数组可以容纳所有替换后的字符。
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return string字符串
*/
public String replaceSpace (String s) {
// write code here
int len=s.length();
char[] c=new char[len*3];
int index=0;
for(int i=0;i<len;i++){
if(s.charAt(i)==' '){
c[index++]='%';
c[index++]='2';
c[index++]='0';
}else{
c[index++]=s.charAt(i);
}
}
return new String(c,0,index);
}
}时间复杂度:O(n)O(n)O(n)。遍历字符串 s 一遍。 空间复杂度:O(n)O(n)O(n)。额外创建字符数组,长度为 s 的长度的 3 倍。

京公网安备 11010502036488号