剑指offer 04 替换空格
来源:互联网 发布:中国邮政数据传媒中心 编辑:程序博客网 时间:2024/06/06 14:24
题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路:
水题!
1.另外开辟一个字符串new_s,遍历s,把s赋值给new_s。空间复杂度O(n)。
2.两个指针。
代码1:
class Solution: # s 源字符串 def replaceSpace(self, s): res = '' for i in s: if i == ' ': res += '%20' else: res += i return res
代码2:
class Solution {public:void replaceSpace(char *str,int length) { //统计空格个数 int spaceCount = 0; int i = 0; for (i = 0; i < length; i ++){ if(str[i] == ' ') spaceCount ++; } int newLength = length + spaceCount * 2;//新长度 int leftindex = length - 1; int rightindex = newLength - 1; while(leftindex >= 0){ if(str[leftindex--] == ' '){ str[rightindex--] = '0'; str[rightindex--] = '2'; str[rightindex--] = '%'; }else{ str[rightindex--] = str[leftindex + 1]; } }}};
阅读全文
0 0
- 剑指offer 04 :替换空格
- 剑指offer 04 替换空格
- [剑指offer]替换空格
- [剑指offer]替换空格
- 剑指offer:替换空格
- 替换空格--《剑指offer》
- 剑指Offer:替换空格
- 【剑指offer】替换空格
- 《剑指Offer》--替换空格
- 剑指offer--替换空格
- 【剑指offer】替换空格
- 【剑指offer】空格替换
- 剑指offer-替换空格
- 剑指offer:替换空格
- [剑指offer]替换空格
- 《剑指offer》替换空格
- 剑指offer:替换空格
- 【剑指Offer】替换空格
- MST 最小生成树
- androidstudio报错之Java.lang.NoClassDefFoundError: de.greenrobot.event.EventBus
- 【JavaScript】我的第6个例子;代码块
- Python数据分析与展示(1)——NumPy库入门
- 个人笔记——jQuery
- 剑指offer 04 替换空格
- 微信支付未安装微信情况下调起支付无响应
- SQL Server 中的 锁
- Unity3d 开始界面空白(黑屏)问题
- Nginx反向代理和负载均衡
- Web交互设计优化方案+check list
- 项目笔记(一)
- 正则表达式
- Python杂记