【剑指offer】5、替换空格

题目

请实现一个函数,把字符串中的每个空格替换成"%20"。例如,We are happy. -> We%20are%20happy.

思路

如果直接从头扫描字符串,碰到空格插入 %20,并将后面的所有字符往后挪,对于O(n)空格的字符串,每次移动O(n)个字符,时间复杂度是O(n2)。

因此,我们先扫描一次,统计出空格的个数,直接计算出替换之后的字符串长度,两个指针分为指向原字符串和替换后字符串的末尾。

  (1)没碰到空格,复制,向头前进

  (2)碰到空格,p1向前近1步,p2复制%20,并前进3步。

直到两个指针相遇。

void replaceSpace(char *str,int length) {
  if (str == nullptr || length <= 0 )
    return;
        
  int num_blank = 0, ogLength = 0;
  int i = 0;   while( str[i] != '\0'){     ogLength++;     if (str[i] == ' ')       num_blank++;     i++;   }   int newLength = ogLength + 2 * num_blank;   if (newLength > length)     return; // length为str字符串的总容量,若替换空格后的长度超过了总容量,则返回。     int index_new = newLength;     int index_og = ogLength;     while( index_og < index_new && index_og >= 0){       if (str[index_og] != ' ')         str[index_new--] = str[index_og];       else{         str[index_new--] = '0';         str[index_new--] = '2';         str[index_new--] = '%'; }       index_og--;     } }

猜你喜欢

转载自www.cnblogs.com/shiganquan/p/9281671.html