替换空格
来源:互联网 发布:矩阵纵横 编辑:程序博客网 时间:2024/06/10 01:21
题目描述:
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则替换之后的字符串为We%20Are%20Happy.
方法一:
class Solution: def replaceSpace(self,s): s = list(s) length = len(s) for i in range(0,length): if s[i]==" ": s[i] = "%20" return ''.join(s)所用时间为7.987545844182548e-05
方法二:使用从后向前移动字符串元素的方法,Python中字符串作为一个常量,需要通过序列切片的方式组合成新的字符串。
s = "we are happy."def replace(s): s_original = s if s == "": return None # 统计原字符串长度 count = 0 # 统计空格数 number_blank = 0 for i in s: count+=1 if i == " ": number_blank+=1 original_len = count new_len = original_len + number_blank*2 index_ori = original_len-1 index_new = new_len-1 # 由*占位扩展之后的字符串长度 s = s+number_blank*2*'*' # 从后向前遍历 while index_ori>=0 and index_new>index_ori: # 空格替换成"%20" if s[index_ori] == " ": s =s[:index_new]+'0'+s[index_new+1:] index_new-=1 s = s[:index_new]+'2'+s[index_new+1:] index_new -= 1 s = s[:index_new]+'%'+s[index_new+1:] index_new -= 1 # 非空格原样向后粘贴 else: s = s[:index_new]+s[index_ori]+s[index_new+1:] index_new -= 1 index_ori-=1 if s == s_original: return "字符串没有空格" return sprint(replace(s))
所用时间为:9.559392215126102e-05
方法一时间较少
拓展:有两个排序的列表a和b,把b中所有数字插入到a中
a = [1,3,4,7]b = [0,5,6,8,9]for i in range(len(b)): for j in range(len(a)): # 当b中元素大于a中最大元素时,直接加在a的后面 if b[i] > a[len(a)-1]: a.append(b[i]) elif b[i] < a[j]: a.insert(j, b[i]) break else: continueprint(a)
阅读全文
0 0
- 空格替换
- 替换空格
- 空格替换
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 空格替换
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- 替换空格
- [LC][Linked List]203. Remove Linked List Elements
- TensorFlow入门(3):基本语法
- 【POJ】2181-Jumping Cows 贪心
- 前后端项目对接流程梳理
- Linux进程间通信-消息队列
- 替换空格
- 配置opencv,丢失 opencv_world300d.dll
- Find Mode in Binary Search Tree:带重复元素的搜索二叉树Morris遍历查找频率最大的元素
- dubbo调用时实现类型丢失
- spring中单例与多例
- iOS 讯飞语音的使用
- .NET笔记系列:LAMBDA表达式常用写法
- 高手处理事情的12个方法
- java集合框架的讲解