替换空格
问题描述
力扣链接
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
解决方案
暴力搜索,后移
通过循环整个字符串,每找到一个空格,替换成“%20”,字符串后面的字符往后移动3位。时间复杂度O(n2)。方法不好。
双指针法(自编码)
1:先找到字符串(s1)中所有的空格数,这样就能直到替换后字符串的长度(s2),s2.length() = s1.length() + count*2;
2:从s1字符串的末尾位字符开始判断是否为空格,如果是,从后往前向s2字符串中写入“%20”,s2的下标先前移动三位,s1的下标向前移动一位;如果不是,将字符从s1复制到s2,下标都前移一位。
3:如果两个下标相等,说明s1字符串前面已经没有空格了。直接将前面相同的字符复制即可。
class Solution {
public String replaceSpace(String s) {
int count = 0; //空格数量计数器
//统计空格的数量
String s1 = s;
while(s1.contains(" ")){
s1 = s1.substring(s1.indexOf(" ")+1);
count++;
}//s1这样处理后会变短,所以不要处理形参
//计算将空格转换成%20后字符串长度
int counttrans = s.length() + count*2-1; //替换后长度
int counts = s.length()-1;
char[] transstring = new char[counttrans+1];
//while(counts <= counttrans && counts >1){
while(count >=0 && counttrans > counts){
if(s.charAt(counts) != ' '){
transstring[counttrans] = s.charAt(counts);
counttrans--;
}else{
transstring[counttrans--] = '0';
transstring[counttrans--] = '2';
transstring[counttrans--] = '%';
}
counts--;
}
//将前面没有空格的字符串替复制到另一个数组
for(int i=0;i<=counttrans;i++){
transstring[i] = s.charAt(i);
}
String re = new String(transstring);
return re;
}
}
时空复杂度都是:O(n);
搜索问题及答案
如何确定字符串中某个字符的个数:
1.可以利用for循环遍历
public class lengthIsIncludeSpace {
public static void main(String[] args) {
String s1 = "1 2 m";
int count2 = 0;
for(int i=0;i<s1.length();i++){
if (s1.charAt(i) == ' ')
count2++;
}
System.out.println(count2);
}
}
2.其他方法:
利用map,键值与数值对应:链接
上面代码中方案:注意会改变原字符串,但是这个还可以统计子字符串。子字符串统计
如何获取字符串中某个指定下标的字符
string.charAt(i);
区别于indexOf()
public int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
建立特定长度的数组
char[] str = new char[10];
设定字符串中特定下标位置的字符
需要利用StringBuilder构造字符串,然后使用setCharAt(index, char)即可。index:位置,char:想要替换的字符。最后使用toString()在转换成字符即可。String类中没有直接方法能够设置某个位置的字符。
如何转换字符数组和字符串
字符数组到字符串:
String string = new String(array);
String string2 = String.valueOf(array);
字符串到字符数组:
String msg = "i am a good boy!";
char[] dest = msg.toCharArray();
官方解法
class Solution {
public String replaceSpace(String s) {
StringBuilder res = new StringBuilder();
for(char c : s.toCharArray())
{
if(c == ' ') res.append("%20");
else res.append(c);
}
return res.toString();
}
}
利用StringBuild构造器。代码解释