mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-30 07:33:45 +00:00
Update 5. 替换空格.md
题目链接改为力扣中的对应题目,题目描述和代码按该题的接口调整。
This commit is contained in:
+11
-27
@@ -2,12 +2,11 @@
|
||||
|
||||
## 题目链接
|
||||
|
||||
[牛客网](https://www.nowcoder.com/practice/0e26e5551f2b489b9f58bc83aa4b6c68?tpId=13&tqId=11155&tab=answerKey&from=cyc_github)
|
||||
[Leetcode](https://leetcode.cn/problems/ti-huan-kong-ge-lcof/)
|
||||
|
||||
## 题目描述
|
||||
|
||||
|
||||
将一个字符串中的空格替换成 "%20"。
|
||||
将一个字符串中的空格替换成 "%20"。(在 LeetCode 上对应原题为 LCR 122. 路径加密,题意要求将 '.' 替换为空格)
|
||||
|
||||
```text
|
||||
Input:
|
||||
@@ -19,34 +18,19 @@ Output:
|
||||
|
||||
## 解题思路
|
||||
|
||||
① 在字符串尾部填充任意字符,使得字符串的长度等于替换之后的长度。因为一个空格要替换成三个字符(%20),所以当遍历到一个空格时,需要在尾部填充两个任意字符。
|
||||
|
||||
② 令 P1 指向字符串原来的末尾位置,P2 指向字符串现在的末尾位置。P1 和 P2 从后向前遍历,当 P1 遍历到一个空格时,就需要令 P2 指向的位置依次填充 02%(注意是逆序的),否则就填充上 P1 指向字符的值。从后向前遍是为了在改变 P2 所指向的内容时,不会影响到 P1 遍历原来字符串的内容。
|
||||
|
||||
③ 当 P2 遇到 P1 时(P2 \<= P1),或者遍历结束(P1 \< 0),退出。
|
||||
|
||||
|
||||
|
||||
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f7c1fea2-c1e7-4d31-94b5-0d9df85e093c.gif" width="350px"> </div><br>
|
||||
① 遍历字符串,统计需要替换字符的个数,据此计算出替换后所需的新长度。
|
||||
② 双指针或 StringBuilder 处理:遍历原字符串,遇到目标字符则追加替换后的内容,其余字符原样复制。
|
||||
|
||||
```java
|
||||
public String replaceSpace(StringBuffer str) {
|
||||
int P1 = str.length() - 1;
|
||||
for (int i = 0; i <= P1; i++)
|
||||
if (str.charAt(i) == ' ')
|
||||
str.append(" ");
|
||||
|
||||
int P2 = str.length() - 1;
|
||||
while (P1 >= 0 && P2 > P1) {
|
||||
char c = str.charAt(P1--);
|
||||
if (c == ' ') {
|
||||
str.setCharAt(P2--, '0');
|
||||
str.setCharAt(P2--, '2');
|
||||
str.setCharAt(P2--, '%');
|
||||
public String pathEncryption(String path) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (char c : path.toCharArray()) {
|
||||
if (c == '.') {
|
||||
sb.append(' ');
|
||||
} else {
|
||||
str.setCharAt(P2--, c);
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
return str.toString();
|
||||
return sb.toString();
|
||||
}
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user