剑指offer编程-替换空格
题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
原数字符数组间够大,在原数组中替换,不开辟新的数组。
思路:
1.从前往后遇到空格就替换成“%20”。考虑到元素覆盖,要不断后移元素。复杂度O(n2)。
2.新字符串长度=原字符串长度+2*字符串中空格数,从后往前替换。代码实现如下。
#include<iostream> using namespace std; class Solution { public: void replaceSpace(char *str, int length) { if (str == NULL || length <= 0) return; int i; int nowlen = 0; int numspace = 0; for (i = 0; str[i] != '\0'; i++){ nowlen++; if (str[i] == ' ') numspace++; } int newlen = nowlen + 2 * numspace; if (newlen <= length){ for (i = nowlen; i >= 0; i--){ if (str[i] != ' ') str[newlen--] = str[i]; else{ str[newlen--] = '0'; str[newlen--] = '2'; str[newlen--] = '%'; } } } else return; } }; #define arrylen 20 int _tmain(int argc, _TCHAR* argv[]) { char str[arrylen] = "We are happy."; Solution s; s.replaceSpace(str, arrylen); for (int i = 0; i < arrylen; i++) cout << str[i]; cout << "按任意键继续……"; cin.clear(); cin.sync(); cin.get(); return 0; }
测试用例:
1.字符串中有空格。(空格在字符串开头、中间、末尾;连续空格)
2.字符串中没有空格;
3.特殊出入测试。(字符串是NULL指针,字符串是一个空字符串,字符串只有一个空格,字符串是连续多个空格)
相似题目:
两个排序的数组A1,A2。内存在A1的末尾有足够的空间容纳A2,把A2中所有数字插入到A1中,并保证插入后依然有序。
从头往尾部插入:需要移动元素,会出现多次复制一个元素的情况,复杂度高!
从尾往头部插入:
#include<iostream> using namespace std; #define arrylen 20 int _tmain(int argc, _TCHAR* argv[]) { int A1[arrylen] = {8,10,35}; int A2[4] = {2,3,5,6}; int A1_len = 3; int A2_len = 4; int new_len = A1_len + A2_len; int p1 = A1_len - 1; int p2 = A2_len - 1; int p = new_len - 1; while ((p1 >= 0)&&(p2>=0)){ if (A2[p2] >= A1[p1]){ A1[p] = A2[p2]; p2--; } else{ A1[p] = A1[p1]; p1--; } p--; } while ( p1 >= 0){ A1[p--] = A1[p1--]; } while ( p2 >= 0){ A1[p--] = A2[p2--]; } for (int i = 0; i < new_len; i++) cout << A1[i]<<" "; cout << "按任意键继续……"; cin.clear(); cin.sync(); cin.get(); return 0; }
这个的测试用例(自己想的,如果不全欢迎补充指教):1.两个数组都不为空(第一个数组都比第二个数组大,第二个数组都比第一个数组大,穿插大小)。
2.特殊情况。(有一个空数组,或都为空数组。)
有道理:
编程,字符串:
char * str = "We are Happy"。字符串长度为13,因为末尾有‘\0’。指针str是指向字符串的指针,若再定义指向该常量字符串的指针,和str实际上指向同一位置。可通过str[i](i<=13)访问字符串,i>13时,越界了,有时是空,有时会发生空间访问冲突。
char str[10]={ "We are Happy"}。预先分配内存,后边补充’\0‘。
注:欢迎批评指正。