Niuke.com C language entry brush questions record

Hello everyone, recently, major Internet layoffs, many people have received graduation notices, and some have stayed at home for more than a week, haven't looked for a job yet, feel that it is not easy to find, and their mood is relatively low . You
will meet in interviews. You can find the answers on Niuke.com for all the questions you have come to:
1. What are the interview questions of Dachang?
2. I panic when I encounter the written test questions. There is no simulated environment
. 3. There is no interviewer to help you simulate the interview
. 4. I have received multiple offers and do not know which one is better?
All questions can be answered here -> poke me to jump directly to brush algorithm questions

If you want to brush the questions, you can go to Niuke.com's "C/C++, Algorithms, Java Classic Interview Questions Daily Practice" is very friendly to Xiaobai

insert image description here

Niuke.com [programming question] replace spaces

Topic description

Please implement a function that replaces each space in a string with "%20". For example, when the string is We Are Happy., the replaced string is We%20Are%20Happy.
insert image description here

topic analysis

Since 1 space occupies 1 character, but if it is replaced with "%20", it is 3 characters. So you need to add a position to the string. Since there are 2 spaces in "we are happy", it is natural to increase 4 positions, that is, increase the length of the string by 4.

Algorithm step

1. First determine how many spaces this string has. The length of the new string is then determined based on the spaces.
2. Move the string after the space to the back in turn.
3. Then fill in the three characters of "%20" in turn.

code

class Solution {
    
    
public:
	void replaceSpace(char *str,int length) {
    
    
	int spacecnt = 0;
	char* cur = str;
	while (*cur)
	{
    
    
		if (*cur == ' ')
		{
    
    
			spacecnt++;
		}
		cur++;
	}
	int newlen = length + spacecnt * 2;
	int end1 = length - 1;
	int end2 = newlen - 1;
	while (end1 != end2)
	{
    
    
		if (str[end1] != ' ')
		{
    
    
			str[end2--] = str[end1--];
		}
		else
		{
    
    
			str[end2--] = '0';
			str[end2--] = '2';
			str[end2--] = '%';
			end1--;
		}
	}
	}
};

Guess you like

Origin blog.csdn.net/qq2466200050/article/details/124330103