cracking the coding interview No1.4
2014-10-19 16:08
393 查看
1.4Write a method to replace all spaces in a string with’%20’,You may assume that the string has sufficient space
at the end of the string to hold the additional characters,and that you are given the “true” length of the string
(Note:if implementing in Java,please use a character array so that you can perform this operation in place);
Answer:
at the end of the string to hold the additional characters,and that you are given the “true” length of the string
(Note:if implementing in Java,please use a character array so that you can perform this operation in place);
Answer:
void replace(char *str) { if (str == NULL) return; int length = strlen(str); if (!length) return; int count = 0; //calculate the number of blank space for (int i = 0; i<length;i++) { if (str[i]==' ') count++; } int totallength = length + 2 * count; str[totallength--] = '\0'; for (int i = length - 1; i>=0; i--) { if (str[i] == ' ') { str[totallength] = '0'; str[totallength-1] = '2'; str[totallength-2] = '%'; totallength -= 3; } else { str[totallength] = str[i]; totallength--; } } }
相关文章推荐
- cracking the coding interview No1.3
- Cracking the Coding Interview Q1.4
- cracking the coding interview No1.5
- cracking the coding interview No1.6
- Cracking The Coding Interview 1.4
- cracking the coding interview No1.7
- cracking the coding interview No1.1
- Cracking The Coding Interview 3rd -- 1.4
- cracking the coding interview No1.2
- cracking the coding interview No1.8
- 《Cracking the Coding Interview》——第18章:难题——题目7
- Cracking the coding interview--Q2.4
- Cracking the coding interview--Q3.2
- Cracking the coding interview--Q1.8
- Cracking the coding interview--Q1.1
- Cracking the coding interview--Q5.5
- Cracking the coding interview--Q4.4
- 《Cracking the Coding Interview》——第3章:栈和队列——题目5
- 《Cracking the Coding Interview》——第4章:树和图——题目3
- 《Cracking the Coding Interview》——第6章:智力题——题目1