替換空格(C++和Python 實現)


(說明:本博客中的題目題目詳細說明參考代碼均摘自 “何海濤《劍指Offer:名企面試官精講典型編程題》2012年”)

題目

    請實現一個函數,把字符串中的每個空格替換為 "%20" 。例如輸入 "We are happy.", 則輸出 "We%20are%20happy." 。

    進一步詳細說明:

    在網絡編程中,如果 URL 參數中含有特殊字符,如空格、'#'、':' 等,可能導致服務器端無法獲得正確的參數值。我們需要這些特殊符號轉換成服務器可以識別的字符。轉換規則是在 '%' 后面跟上 ASCII 碼的兩位十六進制的表示。如空格的 ASCII 碼是 32,即十六進制的 0x20,因此空格被替換成 "%20" 。再比如 '#' 的 ASCII 碼為 35,即十六進制的 0x23,它在 URL 中被替換為 "%32"。再比如 ':' 的 ASCII 碼為 50,即十六進制的 0x32,它在 URL 中被替換為 "%32"。

 

算法設計思想

1. 時間復雜度為 O(n2) 的算法思想

    從頭到尾,掃描字符串中的每個字符,遇到空格,先將剩余的字符(未遍歷到的字符串)整體向后移動2個位置,然后,在空格和其后的2個字符的替換為"%20"。

2. 時間復雜度為 O(n) 的算法思想

    先遍歷整個字符串,計算字符串中空格的總數,從而可以計算出替換后的字符串長度(根據替換規則,每次替換空格時,都會使字符串的長度增加2)。然后,使用兩個指針或索引,從后往前遍歷,即初始化指針或索引分別指向替換前和替換后字符串的末尾,循環遞減,如遇到空格,則替換為 "%20",從而減少字符串移動的次數,降低時間復雜度。

 

C++ 實現

#include <iostream>

// Replace blank " " with "%20" // Note - the 'length' parameter is the maximum length of the array
void ReplaceBlanks(char str[], int length) { if (str == NULL || length <= 0) // 易漏點 return; // Count the number of blanks
    char *pChar = str; int strLen = 0; int blanksCount = 0; while (*pChar++ != '\0') { // 易錯點,容易漏掉指針遞增操作,而導致運行時的死循環。 ++strLen; if (*pChar == ' ') blanksCount++; } // Compute the replaced string length
    int replacedStrLen = strLen + 2 * blanksCount; if (replacedStrLen > length) { std::cout << "The char array is lack of space." << std::endl; return; } // Char pointer initialization
    char *pChar2 = str + replacedStrLen - 1; pChar = str + strLen - 1; while (pChar != pChar2) { // Replace blanks with "%20"
        if (*pChar == ' ') { pChar2 -= 2; *pChar2 = '%'; *(pChar2 + 1) = '2'; *(pChar2 + 2) = '0'; } else { *pChar2 = *pChar; } --pChar; --pChar2; } } void unitest() { char s[100] = "We are happy."; std::cout << "Before replacing blanks, the string is " << s << std::endl; ReplaceBlanks(s, 100); std::cout << "After replacing blanks, the string is " << s << std::endl; } int main() { unitest(); return 0; }

 

Python 實現

#!/usr/bin/python # -*- coding: utf8 -*-

# Replace blank " " with "%20" # Note, the 'string' parameter is Python list type; # and the 'length' parameter is the maximum length of the array.
def replace_blanks(string, length): if string == None or length <= 0: # 易漏點 return

    # Count the number of blanks
    blanks_count = string.count(' ') string_length = len(string) # Compute the replaced string length
    replaced_length = string_length + 2 * blanks_count if replaced_length > length: return
    # Extend the char list length 'string_length' with '' characters
    string += ["" for i in range(replaced_length - string_length)] # Replace each blank with "%20"
    original_index = string_length - 1 new_index = replaced_length - 1
    while new_index != original_index: if string[original_index] == ' ': new_index -= 2 string[new_index:new_index+3] = '%20'
        else: string[new_index] = string[original_index] # Update indexes
        new_index -= 1 original_index -= 1


def unitest(): test_string = "We are happy." string_lst = list(test_string) # 易錯點不能用'str'對象替代,因為 'str' object does not support item assignment 。 print "Before replacing blanks, the string is %s" % ''.join(string_lst) replace_blanks(string_lst, 100) print "After replacing blanks, the string is %s" % ''.join(string_lst) if __name__ == '__main__': unitest()

 

參考代碼

1. targetver.h

#pragma once

// The following macros define the minimum required platform. The minimum required platform // is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run // your application.  The macros work by enabling all features available on platform versions up to and 
// including the version specified. // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. #ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista. #define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows. #endif

2. stdafx.h

// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // 
#pragma once #include "targetver.h" #include <stdio.h> #include <tchar.h>



// TODO: reference additional headers your program requires here

3. stdafx.cpp

// stdafx.cpp : source file that includes just the standard includes // ReplaceBlank.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information
 #include "stdafx.h"

// TODO: reference any additional headers you need in STDAFX.H // and not in this file

4. ReplaceBlank.cpp

// ReplaceBlank.cpp : Defines the entry point for the console application. //

// 《劍指Offer——名企面試官精講典型編程題》代碼 // 著作權所有者:何海濤
 #include "stdafx.h" #include <string>

/*length 為字符數組string的總容量*/
void ReplaceBlank(char string[], int length) { if(string == NULL && length <= 0) return; /*originalLength 為字符串string的實際長度*/
    int originalLength = 0; int numberOfBlank = 0; int i = 0; while(string[i] != '\0') { ++ originalLength; if(string[i] == ' ') ++ numberOfBlank; ++ i; } /*newLength 為把空格替換成'%20'之后的長度*/
    int newLength = originalLength + numberOfBlank * 2; if(newLength > length) return; int indexOfOriginal = originalLength; int indexOfNew = newLength; while(indexOfOriginal >= 0 && indexOfNew > indexOfOriginal) { if(string[indexOfOriginal] == ' ') { string[indexOfNew --] = '0'; string[indexOfNew --] = '2'; string[indexOfNew --] = '%'; } else { string[indexOfNew --] = string[indexOfOriginal]; } -- indexOfOriginal; } } void Test(char* testName, char string[], int length, char expected[]) { if(testName != NULL) printf("%s begins: ", testName); ReplaceBlank(string, length); if(expected == NULL && string == NULL) printf("passed.\n"); else if(expected == NULL && string != NULL) printf("failed.\n"); else if(strcmp(string, expected) == 0) printf("passed.\n"); else printf("failed.\n"); } // 空格在句子中間
void Test1() { const int length = 100; char string[length] = "hello world"; Test("Test1", string, length, "hello%20world"); } // 空格在句子開頭
void Test2() { const int length = 100; char string[length] = " helloworld"; Test("Test2", string, length, "%20helloworld"); } // 空格在句子末尾
void Test3() { const int length = 100; char string[length] = "helloworld "; Test("Test3", string, length, "helloworld%20"); } // 連續有兩個空格
void Test4() { const int length = 100; char string[length] = "hello world"; Test("Test4", string, length, "hello%20%20world"); } // 傳入NULL
void Test5() { Test("Test5", NULL, 0, NULL); } // 傳入內容為空的字符串
void Test6() { const int length = 100; char string[length] = ""; Test("Test6", string, length, ""); } //傳入內容為一個空格的字符串
void Test7() { const int length = 100; char string[length] = " "; Test("Test7", string, length, "%20"); } // 傳入的字符串沒有空格
void Test8() { const int length = 100; char string[length] = "helloworld"; Test("Test8", string, length, "helloworld"); } // 傳入的字符串全是空格
void Test9() { const int length = 100; char string[length] = "   "; Test("Test9", string, length, "%20%20%20"); } int _tmain(int argc, _TCHAR* argv[]) { Test1(); Test2(); Test3(); Test4(); Test5(); Test6(); Test7(); Test8(); Test9(); return 0; }

5. 項目 04_ReplaceBlank 下載

百度網盤: 04_ReplaceBlank.zip

 

參考資料

[1]  何海濤. 劍指 Offer:名企面試官精講典型編程題 [M]. 北京:電子工業出版社,2012. 44-48.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM