替换空格

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

 1 # -*- coding:utf-8 -*-
 2 class Solution:
 3     # s 源字符串
 4     def replaceSpace(self, s):
 5         n = len(s)
 6         whitespace = 0
 7         for ss in s:
 8             if ss ==' ':
 9                 whitespace += 1
10         ary = [' '] * (n + whitespace * 2)
11         idx = n + whitespace * 2 - 1
12         for i in range(n-1,-1,-1):
13             if s[i] == ' ':
14                 ary[idx] = '0'
15                 idx -= 1
16                 ary[idx] = '2'
17                 idx -= 1
18                 ary[idx] = '%'
19                 idx -= 1
20             else:
21                 ary[idx] = s[i]
22                 idx -= 1
23         s = ''
24         s = ''.join(ary)
25         return s
26         # write code here

先计算出扩展后的字符串的长度然后,从后向前遍历,遇到空格,逆序依次插入对应的三个字符。

 

leetcode地址,Java版代码:

 1 class Solution {
 2     public String replaceSpace(String s) {
 3         StringBuilder str = new StringBuilder(s);
 4         int P1 = str.length() - 1;
 5         for (int i = 0; i <= P1; i++)
 6         if (str.charAt(i) == ' '){
 7             str.append("  ");//这里补充2个空格
 8         }
 9         int P2 = str.length() - 1;
10         while (P1 >= 0 && P2 > P1) {
11             char c = str.charAt(P1--);
12             if (c == ' ') {
13                 str.setCharAt(P2--, '0');
14                 str.setCharAt(P2--, '2');
15                 str.setCharAt(P2--, '%');
16             } else {
17                 str.setCharAt(P2--, c);
18             }
19         }
20         return str.toString();
21     }
22 }

 

posted on 2019-06-12 21:59  Sempron2800+  阅读(123)  评论(0编辑  收藏  举报