輸入兩個字符串,從第一字符串中刪除第二個字符串中所有的字符


例如,輸入”They are students.””aeiou”,則刪除之后的第一個字符串變成”Thy r stdnts.”

思路:不可避免的是遍歷第一個字符串,如果遍歷一個字符,都需要去第二個字符串中查找其存不存在,那么復雜度會是O(nm),當然由於字符數有限,所以m是個常量。關於查找速度最快的當然是hash表,對於8位字符,size=2^8足矣。

關於刪除字符,后面的字符要往前移,如果每刪除一個就移一次,O(n^2)這復雜度實在太高,僅僅用快慢指針就可以搞定,這個方法非常有用,比如求解循環鏈表。

初始化:快慢指針指向第一個字符

循環:如果快指針指的是不需要的字符,將值賦給慢指針后,快慢指針同時++;如果快指針指向待刪除字符,那么直接++;

終止:快指針指向'\0'

 

  1. /*     
  2. * Copyright (c) 2011 alexingcool. All Rights Reserved.     
  3. */  
  4. #include <iostream>  
  5.   
  6. #define NUMBER 256  
  7.   
  8. using namespace std;  
  9.   
  10. char firstArray[] = "They are students.";  
  11. char secondArray[] = "aeiou";  
  12. const int firstSize = sizeof firstArray / sizeof *firstArray;  
  13. const int secondSize = sizeof secondArray / sizeof *secondArray;  
  14.   
  15. bool flag[NUMBER];  
  16.   
  17. void deleteArray(char *firstArray, char *secondArray)  
  18. {  
  19.     if(firstArray == NULL || secondArray == NULL)  
  20.         return;  
  21.   
  22.     for(int i = 0; i < NUMBER; i++) {  
  23.         flag[i] = false;  
  24.     }  
  25.   
  26.     for(int i = 0; i < secondSize; i++) {  
  27.         int pos = static_cast<int>(secondArray[i]);  
  28.         flag[pos] = true;  
  29.     }  
  30.   
  31.     char *fast = firstArray, *slow = firstArray;  
  32.   
  33.     while(*fast != '\0') {  
  34.         if(flag[*fast] == false) {  
  35.             *slow = *fast;  
  36.             slow++;  
  37.         }  
  38.         fast++;  
  39.     }  
  40.     *slow = 0;  
  41. }  
  42.   
  43. void main()  
  44. {  
  45.     deleteArray(firstArray, secondArray);  
  46.     cout << firstArray << endl;  
  47. }  


結果如下:


免責聲明!

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



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