当前位置:网站首页>Leetcode——剑指 Offer 05. 替换空格
Leetcode——剑指 Offer 05. 替换空格
2022-07-07 12:15:00 【styfish】
概述
分析
这题,如果不限制空间复杂度,其实很简单,直接开一个新的
string
就可以实现了但是,如果要求只能原理处理呢?这里有一个问题需要解决:
s --> %20
,增加了字符,需要增加striing的容量因为
push_back
之能最末尾操作
思路
增加容量
- 可以先遍历一遍string,统计空格的个数,就可以知道最终需要扩充的大小了
- 然后利用
resize()
来扩充大小
代码
class Solution {
public:
string replaceSpace(string s) {
int count = 0; // 统计空格的个数
int sOldSize = s.size();
for (int i = 0; i < s.size(); i++) {
if (s[i] == ' ') {
count++;
}
}
// 扩充字符串s的大小,也就是每个空格替换成"%20"之后的大小
s.resize(s.size() + count * 2);
// 为了原地操作,所以使用双指针法
int ptr = s.size() - 1, wokr_ptr = sOldSize - 1;
// 这里要从后往前,因为如果添加新元素从前往后,会覆盖掉原始的元素(
for(; wokr_ptr >= 0; --wokr_ptr) {
if (s[wokr_ptr] != ' ') s[ptr--] = s[wokr_ptr];
else {
s[ptr] = '0';
s[ptr - 1] = '2';
s[ptr - 2] = '%';
ptr -= 3;
}
}
return s;
}
};
边栏推荐
- 请问,我kafka 3个分区,flinksql 任务中 写了 join操作,,我怎么单独给join
- Cesium knows the longitude and latitude of one point and the distance to find the longitude and latitude of another point
- Horizontal of libsgm_ path_ Interpretation of aggregation program
- 566. Reshaping the matrix
- 接口自动化测试-接口间数据依赖问题解决
- 2022-7-6 beginner redis (I) download, install and run redis under Linux
- [fortress machine] what is the difference between cloud fortress machine and ordinary fortress machine?
- AI人才培育新思路,这场直播有你关心的
- THINKPHP框架的优秀开源系统推荐
- Environment configuration of lavarel env
猜你喜欢
Wired network IP address of VMware shared host
一个简单LEGv8处理器的Verilog实现【四】【单周期实现基础知识及模块设计讲解】
"Song of ice and fire" in the eleventh issue of "open source Roundtable" -- how to balance the natural contradiction between open source and security?
UML 顺序图(时序图)
Vmware 与主机之间传输文件
使用day.js让时间 (显示为几分钟前 几小时前 几天前 几个月前 )
118. Yanghui triangle
Evolution of customer service hotline of dewu
Assign a dynamic value to the background color of DataGrid through ivalueconverter
Data flow diagram, data dictionary
随机推荐
Excerpt from "misogyny: female disgust in Japan"
Common response status codes
The meaning of variables starting with underscores in PHP
C # switch pages through frame and page
"Song of ice and fire" in the eleventh issue of "open source Roundtable" -- how to balance the natural contradiction between open source and security?
Advanced Mathematics - Chapter 8 differential calculus of multivariate functions 1
Beginner XML
Co create a collaborative ecosystem of software and hardware: the "Joint submission" of graphcore IPU and Baidu PaddlePaddle appeared in mlperf
2022-7-7 Leetcode 34. Find the first and last positions of elements in a sorted array
Is the compass stock software reliable? Is it safe to trade stocks?
Best practice | using Tencent cloud AI willingness to audit as the escort of telephone compliance
请问,redis没有消费消息,都在redis里堆着是怎么回事?用的是cerely 。
PC端页面如何调用QQ进行在线聊天?
XML文件的解析操作
Realization of search box effect [daily question]
杭电oj2092 整数解
call undefined function openssl_ cipher_ iv_ length
搜索引擎接口
高等数学---第八章多元函数微分学1
IP address home location query full version