替换空格
实现一个函数,把字符串中的每个空格替换成“%20”。例如”we are happy.”,则输出”we%20are%20happy.”
思路
两种方案:
- 在原来的字符串上进行替换,可能覆盖修改在该字符串后面的内存。
- 创建新的字符串并在新的字符串上进行替换,可以分配足够多的内存。(计算出当前字符串存在的空格数量,需要开辟新的字符空间为originalLength + spaceLength*2,往后向前遍历,遇到空格在相应的位置加入”%20”,即是所求)
代码
function replaceSpace(string) {
if (string.length === 0 || !string) {
return;
}
let originalLength = string.length;
let spaceLength = 0;
let index = 0;
while (index < originalLength) {
if (string[index] === " ") {
spaceLength++;
}
index++;
}
let newLength = originalLength + spaceLength * 2;
let indexOfOriginal = originalLength;
let indexOfNew = newLength;
let newString = new Array(newLength);
while (indexOfOriginal >= 0 && indexOfNew >= indexOfOriginal) {
if (string[indexOfOriginal - 1] === " ") {
newString[--indexOfNew] = '0';
newString[--indexOfNew] = '2';
newString[--indexOfNew] = '%';
} else {
newString[--indexOfNew] = string[indexOfOriginal - 1];
}
indexOfOriginal--;
}
return newString.join("");
}
复杂度分析
- 时间复杂度: O(N)
- 空间复杂度: O(N)
FEATURED TAGS
前端开发
H5
JavaScript
设计模式
browser
jQuery
源码分析
生活
leetcode
Array
Stack
Queue
Linked List
剑指offer
Binary Search Tree
Binary Tree
Breadth-First Search
Depth-First Search
String
Set
Binary Search
Sliding Window
Backtracking
Dynamic Programming
Two Pointers
Union Find
Sort
Bit Operation
Recursion
Map
Graph
Search
Hash
LinkedList
复盘
QuickSort
Trie
Design
MinHeap
Traverse
Min Heap
Node.js
BackEnd
SQL
MySQL
Design Patterns
Network
计算机网络
Python
SVG