当前位置:网站首页>剑指 Offer 05. 替换空格
剑指 Offer 05. 替换空格
2022-07-05 08:16:00 【程序员·小李】
题目:
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
思路:
1. 先进行一次遍历,查看空格的个数,空格需要替换成“%20”,因此需要对数组进行扩容。array.length - count + count * 3便是替换后数组的大小。
2. 从后向前依次复制。
class Solution {
public String replaceSpace(String s) {
if (s == null){
return null;
}
char[] array = s.toCharArray();
int count = 0;
for (char c : array){
if (c == ' '){
count++;
}
}
char[] newArray = new char[array.length - count + count * 3];
int pointer = newArray.length - 1;
for (int j = array.length - 1; j >= 0; j--){
if (array[j] != ' '){
newArray[pointer--] = array[j];
continue;
}
newArray[pointer--] = '0';
newArray[pointer--] = '2';
newArray[pointer--] = '%';
}
return new String(newArray);
}
}
边栏推荐
- Basic embedded concepts
- Step motor generates S-curve upper computer
- Several important parameters of LDO circuit design and type selection
- Zero length array in GNU C
- Compilation warning solution sorting in Quartus II
- C WinForm [view status bar -- statusstrip] - Practice 2
- STM32---IIC
- Introduction of air gap, etc
- Shell script basic syntax
- PMSM dead time compensation
猜你喜欢

Soem EtherCAT source code analysis attachment 1 (establishment of communication operation environment)

Several important parameters of LDO circuit design and type selection

Nb-iot technical summary

Compilation warning solution sorting in Quartus II

Simple design description of MIC circuit of ECM mobile phone

Semiconductor devices (III) FET

【论文阅读】2022年最新迁移学习综述笔注(Transferability in Deep Learning: A Survey)

MySQL之MHA高可用集群

实例009:暂停一秒输出

Semiconductor devices (I) PN junction
随机推荐
Connection mode - bridge and net
STM32 single chip microcomputer - external interrupt
Halcon's practice based on shape template matching [1]
Network communication model -- Network OSI tcp/ip layering
99 multiplication table (C language)
Weidongshan Internet of things learning lesson 1
OLED 0.96 inch test
Shape template matching based on Halcon learning [v] find_ cocoa_ packages_ max_ deformation. Hdev routine
Bluetooth hc-05 pairing process and precautions
实例003:完全平方数 一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
Factors affecting the quality of slip rings in production
关于线性稳压器的五个设计细节
实例007:copy 将一个列表的数据复制到另一个列表中。
STM32 single chip microcomputer - bit band operation
My-basic application 1: introduction to my-basic parser
Design a clock frequency division circuit that can be switched arbitrarily
Hardware 1 -- relationship between gain and magnification
Shape template matching based on Halcon learning [vi] find_ mirror_ dies. Hdev routine
Arduino uses nrf24l01+ communication
MySQL之MHA高可用集群