classSolution{publicStringreplaceSpace(String s){int len = s.length();StringBuffer str =newStringBuffer();for(int i =0; i < len ; i++){if(s.charAt(i)==' ') str.append("%20");//遇到空格就在尾部拼接%20else str.append(s.charAt(i));//遇到字符就在尾部正常拼接字符}return str.toString();}}
方法二:双指针做法
classSolution{publicStringreplaceSpace(String s){int len = s.length();StringBuffer str =newStringBuffer(s);if( len ==0)return"";for(int i =0; i< len ; i++)if(s.charAt(i)==' ') str.append(" ");//扩充空间,空格数量2倍String string = str.toString();char[] strs = string.toCharArray();int left = s.length()-1;int right = str.length()-1;while(left >=0){if(str.charAt(left)==' '){
strs[right--]='0';
strs[right--]='2';
strs[right]='%';}else strs[right]= strs[left];
right--;
left--;}returnnewString(strs);}}