table of Contents
To prove safety Offer- face questions 5 --- replace spaces
1 Introduction
Implement a function, each space in the replacement string as "20%." For example, type "Hello World", the output "Hello% 20World".
2, problem solution
Not recommended Method 1: traverse front to back, every encounter spaces and replace all the characters back to move backward.
Time complexity: O (n ^ 2)
Recommended Method 2: traversal from back to front, the detailed process of looking at the code.
Time complexity: O (n)
///arr是要修改的字符串,length表示这个字符串的最大长度
void ChangeSpace(char arr[], int length)
{
if (arr == nullptr || length<=0)
{
return;
}
int i = 0;
//字符串实际长度
int arrLength = 0;
//空格个数
int spaceNum = 0;
while (arr[i] != '\0')
{
if (arr[i] == ' ')
spaceNum++;
arrLength++;
i++;
}
//新字符串需要的长度
int newArrLength = arrLength + spaceNum * 2;
if (newArrLength > length)
return;
//从后向前依次比较替换
while (arrLength >= 0 && newArrLength > arrLength)
{
if (arr[arrLength] == ' ')
{
arr[newArrLength] = '0';
arr[newArrLength-1] = '2';
arr[newArrLength-2] = '%';
arrLength--;
newArrLength-=3;
}
else {
arr[newArrLength] = arr[arrLength];
arrLength--;
newArrLength--;
}
}
}
3, deformation title
There are two sorted array a1 and a2, a1 at the end of memory has enough free time receiving a2. Implement a function, all numbers a2 a2 insert, and all of the numbers are sorted.
///需要排序的两个数组和其各自的长度
void Sort(int arr1[], int arr2[], int length1, int length2)
{
if (arr1 == nullptr || arr2 == nullptr || length2<=0)
{
return;
}
//总长度
int length = length1 + length2;
//从后向前依次比较
while (length1 >= 0 && length > length1)
{
if (arr1[length1-1] >= arr2[length2-1])
{
arr1[length - 1] = arr1[length1 - 1];
length--;
length1--;
}
else {
arr1[length - 1] = arr2[length2 - 1];
length--;
length2--;
}
}
}