替换空格

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

https://www.nowcoder.com/questionTerminal/4060ac7e3e404ad1a894ef3e17650423

 易得每替换一个空格,字符串长度都会增加2,假设要替换n个空格,则字符串总长度增加2*n, 设原来字符串长度为m, 设i = m - 1, j = m - 1 + 2 * n,从后往前扫描,如果s[i] 不是空格,

s[j] = s[i],把字符串往后挪,给空格替换腾出空间,如果则把空格替换为%20,j = j - 3.

 1 public class Solution {
 2     public String replaceSpace(StringBuffer str) {
 3         int n = str.length();
 4         int sum = 0;
 5         for (int i = 0; i < n; ++i) {
 6             if (str.charAt(i) == ' ') sum++;
 7         }
 8         System.out.println(n);
 9         str.setLength(n + sum * 2);
10         
11         int i = n - 1, j = i + sum * 2;
12         while (i >= 0) {
13             if (str.charAt(i) == ' ') {
14                 str.setCharAt(j--, '0');
15                 str.setCharAt(j--, '2');
16                 str.setCharAt(j--, '%');
17                 i--;
18                
19             } else {
20                 str.setCharAt(j, str.charAt(i));
21                 j--;i--;
22                 
23             }
24             
25         }
26         return str.toString();
27     }
28 }
View Code
原文地址:https://www.cnblogs.com/hyxsolitude/p/12238694.html