替换空格
1. 题目形容
请实现一个函数,将一个字符串中的空格替换成“%20”。
2. 示例
例如,当字符串为We Are Happy.则通过替换之后的字符串为We%20Are%20Happy。
3. 解题思路
此题比较简单
第一种办法:新开一个内存空间,遍历原字符串数组,如果碰到字符为空格,则append %20进新的空间
第二种办法:不开拓新的空间,首先统计空格数量,从而计算出新的空间大大小,从前面往前面挪动。
4. Java实现
办法一:新开一个内存空间
// 新开一个内存空间public class Solution { public String replaceSpace(StringBuffer str) { //创立一个新的空间 StringBuffer out = new StringBuffer(); for (int i = 0; i < str.length(); i++){ char a = str.charAt(i); if (a == ' '){ out.append("%20"); }else{ out.append(a); } } return out.toString(); }}
办法二:不开拓新的空间,从前面往前面挪动
public class Solution { public String replaceSpace(StringBuffer str) { // 计算空格的数量 int spaceNum = 0; for (int i = 0; i < str.length(); i++){ char a = str.charAt(i); if (a == ' '){ spaceNum ++; } } // 开拓空间 int oldIndex = str.length()-1; // 原字符串的下标 int newLength = str.length() + spaceNum * 2; int newIndex = newLength -1; str.setLength(newLength); // 从新设置字符串的长度 while(newIndex >= 0){ if (str.charAt(oldIndex) != ' '){ str.setCharAt(newIndex, str.charAt(oldIndex)); oldIndex --; newIndex --; }else{ str.setCharAt(newIndex--, '0'); str.setCharAt(newIndex--, '2'); str.setCharAt(newIndex--, '%'); oldIndex--; // 只进行一次减 1 } } return str.toString(); }}
5. Python实现
办法一:下列的字符串是 不可变对象,应用 + 操作时,会产生许多的对象,所以最好应用第二种办法
class Solution(): def replaceSpace(self, s): if type(s) != str: return new_s = '' for sr in s: if sr == ' ': new_s += '%20' else: new_s += sr return new_s so = Solution()s = ' ab c d e 'print(so.replaceSpace(s))# %20ab%20c%20d%20e%20print(s.replace(' ', '%20'))
办法二:转换成列表模式
class Solution: def replaceSpace(self, s): if type(s) != str: return li = list(s) for i in range(len(li)): if li[i] == ' ': li[i] = '%20' res = "".join(li) return resso = Solution()s = ' ab c d e 'print(so.replaceSpace(s))
如果您感觉本文有用,请点个“在看”