如何制作网站效果图,做农村电商要多少钱,苏州专业做网站,网站开发android客户端1 问题场景
编写一种方法#xff0c;将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符#xff0c;并且知道字符串的“真实”长度。
注意#xff1a;字符串长度在 [0, 500000] 范围内。 2 答案
2.1 解决方案一
直接使用String方法解决 public s…1 问题场景
编写一种方法将字符串中的空格全部替换为%20。假定该字符串尾部有足够的空间存放新增字符并且知道字符串的“真实”长度。
注意字符串长度在 [0, 500000] 范围内。 2 答案
2.1 解决方案一
直接使用String方法解决 public static String replaceSpaces(String S, int length) {if(S.length()500000||S.length()0){return 字符长度超出合理范围;}S S.substring(0,length).replace( ,%20);return S;}
进行测试
package com.example.demo;public class Solution {public static void main(String[] args) {System.out.println(replaceSpaces( ,5));}public static String replaceSpaces(String S, int length) {if(S.length()500000||S.length()0){return 字符长度超出合理范围;}S S.substring(0,length).replace( ,%20);return S;}}2.2 解决方案二
package com.example.demo;public class Solution {public static void main(String[] args) {System.out.println(replaceSpaces( ,5));}public static String replaceSpaces(String S, int trueLength) {if(S.length()500000||S.length()0){return 字符长度超出合理范围;}char[] str S.toCharArray();int spaceCount 0, index, i 0;// 计算空格的数量for (i 0; i trueLength; i) {if (str[i] ) {spaceCount;}}// 计算替换后的字符串长度index trueLength spaceCount * 2;// 计算替换后的字符串长度index trueLength spaceCount * 2;// 从后向前操作进行替换if (trueLength str.length) str[trueLength] \0; // 标记实际结束位置for (i trueLength - 1; i 0; i--) {if (str[i] ) {str[index - 1] 0;str[index - 2] 2;str[index - 3] %;index index - 3;} else {str[index - 1] str[i];index--;}}return new String(str);}}