面试题4:替换空格

代码如下:

 1 # -*- coding: utf-8 -*-
 2 """
 3 @File:Replace_spaces_1.py
 4 @E-mail:364942727@qq.com
 5 @Time:2019-12-20 10:54 
 6 @Author:Nobita   
 7 @Version:1.0   
 8 @Desciption:面试题4:替换空格
 9 """
10 
11 import time
12 '''
13 题目:
14 请实现一个函数,把字符串中的每个空格替换成“%20”。
15 例如输入“We are happy.”,则输出“We%20are%20happy.”。
16 '''
17 
18 class Solution:
19     # write code here.
20     def replaceSpaces_1(self, s):
21         '''方法一:
22         利用python自带的append()方法解题
23         '''
24         if not isinstance(s, str) or len(s) <= 0 or s == None:
25             return ''
26         result = []
27         for i in s:
28             if i == ' ':
29                 result.append('%20')
30             else:
31                 result.append(i)
32         return ''.join(result)
33 
34     # write code here.
35     def replaceSpaces_2(self, s):
36         '''方法二:
37         先计算最终需要给出的长度,然后建立两个指针p1,p2;p1指向原始字符串的末尾,p2指向替换后的字符串的末尾。
38         同时移动p1,p2, 将p1指的内容逐个复制到p2, 当p1遇到空格时:在p2处插入%20,p1向前移动一个位置,p2向前移动3个位置,当p1和p2位置重合时,全部替换完成。
39         '''
40         if not isinstance(s, str) or len(s) <= 0 or s == None:
41             return ''
42         numberOfBlack = 0
43         for i in s:
44             if i == ' ':
45                 numberOfBlack += 1
46 
47         originalLenth = len(s)
48         newStrLenth = 2 * numberOfBlack + originalLenth
49         indexOfOriginal = originalLenth - 1
50         indexOfNew = newStrLenth - 1
51         newStr = newStrLenth * [None]
52         while indexOfNew >= 0 and indexOfOriginal <= indexOfNew:
53             if s[indexOfOriginal] == ' ':
54                 newStr[indexOfNew - 2: indexOfNew + 1] = ['%', '2', '0']
55                 indexOfNew -= 3
56                 indexOfOriginal -= 1
57             else:
58                 newStr[indexOfNew] = s[indexOfOriginal]
59                 indexOfNew -= 1
60                 indexOfOriginal -= 1
61         return ''.join(newStr)
62 
63 if __name__ == '__main__':
64     s = 'We are happy.'
65     b = ''
66     for i in range(8000000):
67         b += s
68 
69     #方法一运行时间:
70     startTime_1 = time.perf_counter()
71     Solution().replaceSpaces_1(b)
72     endTime_1 = time.perf_counter()
73     print('Time Used:', endTime_1 - startTime_1)
74 
75     #方法二运行时间:
76     startTime_2 = time.perf_counter()
77     Solution().replaceSpaces_2(b)
78     endTime_2 = time.perf_counter()
79     print('Time Used:', endTime_2 - startTime_2)

两种方法运行时间比较结果如下:

自测代码:

 1 # -*- coding: utf-8 -*-
 2 """
 3 @File:test_ReplaceSpaces.py    
 4 @E-mail:364942727@qq.com
 5 @Time:2019-12-20 13:16 
 6 @Author:Nobita   
 7 @Version:1.0   
 8 @Desciption:对ReplaceSpaces函数进行单元测试
 9 """
10 
11 import unittest
12 from .Replace_spaces import Solution
13 
14 
15 class TestReplaceSpaces(unittest.TestCase):
16     # write code here.
17     def test_01_LeftSpacesStr(self):
18         '''空格在字符串左边'''
19         s = '   helloworld'
20         result_1 = Solution().replaceSpaces_1(s)
21         result_2 = Solution().replaceSpaces_2(s)
22         print('空格在字符串左边,方法一运算结果:{},方法二运算结果:{}'.format(result_1, result_2))
23 
24     def test_02_RightSpacesStr(self):
25         '''空格在字符串右边'''
26         s = 'helloworld   '
27         result_1 = Solution().replaceSpaces_1(s)
28         result_2 = Solution().replaceSpaces_2(s)
29         print('空格在字符串右边,方法一运算结果:{},方法二运算结果:{}'.format(result_1, result_2))
30 
31     def test_03_RightLeftSpacesStr(self):
32         '''空格在字符串两边'''
33         s = '   helloworld   '
34         result_1 = Solution().replaceSpaces_1(s)
35         result_2 = Solution().replaceSpaces_2(s)
36         print('空格在字符串两边,方法一运算结果:{},方法二运算结果:{}'.format(result_1, result_2))
37 
38     def test_04_MidSpacesStr(self):
39         '''空格在字符串中间'''
40         s = 'hello   world'
41         result_1 = Solution().replaceSpaces_1(s)
42         result_2 = Solution().replaceSpaces_2(s)
43         print('空格在字符串中间,方法一运算结果:{},方法二运算结果:{}'.format(result_1, result_2))
44 
45     def test_05_NoneSpacesStr(self):
46         '''字符串中没有空格'''
47         s = 'helloworld'
48         result_1 = Solution().replaceSpaces_1(s)
49         result_2 = Solution().replaceSpaces_2(s)
50         print('字符串中没有空格,方法一运算结果:{},方法二运算结果:{}'.format(result_1, result_2))
51 
52     def test_06_StrIsNull(self):
53         '''空字符串'''
54         s = ''
55         result_1 = Solution().replaceSpaces_1(s)
56         result_2 = Solution().replaceSpaces_2(s)
57         print('空字符串,方法一运算结果:{},方法二运算结果:{}'.format(result_1, result_2))
58 
59     def test_07_TypeNotStr(self):
60         '''输入类型不是字符串'''
61         s = 123456789
62         result_1 = Solution().replaceSpaces_1(s)
63         result_2 = Solution().replaceSpaces_2(s)
64         print('输入类型不是字符串,方法一运算结果:{},方法二运算结果:{}'.format(result_1, result_2))
65 
66     def test_08_OnlyOneSpaceStr(self):
67         '''只输入一个空格'''
68         s = ' '
69         result_1 = Solution().replaceSpaces_1(s)
70         result_2 = Solution().replaceSpaces_2(s)
71         print('只输入一个空格,方法一运算结果:{},方法二运算结果:{}'.format(result_1, result_2))
72 
73 
74 if __name__ == '__main__':
75     unittest.main()
原文地址:https://www.cnblogs.com/chenshengkai/p/12072720.html