class Solution { public String replaceSpace(String s) { return s.replaceAll(" ", "%20"); } }
- 创建StringBuilder
- 循环遍历字符串
- 字符为 ‘ ’(空格),使用append(),添加”%20“
- 字符不为空格,使用append(), 添加原字符
class Solution { public String replaceSpace(String s) { StringBuilder s2 = new StringBuilder(); for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if (c == ' '){ s2.append("%20"); } else { s2.append(c); } } return s2.toString(); } }
因为知道替换字符是1个替换3个,所以可以创建最大长度为length*3
class Solution { public String replaceSpace(String s) { int length = s.length(); char[] array = new char[length * 3]; int size = 0; for (int i = 0; i < length; i++) { char c = s.charAt(i); if (c == ' ') { array[size++] = '%'; array[size++] = '2'; array[size++] = '0'; } else { array[size++] = c; } } String newStr = new String(array, 0, size); return newStr; } } 作者:LeetCode-Solution 链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/solution/mian-shi-ti-05-ti-huan-kong-ge-by-leetcode-solutio/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。