例如,輸入”They are students.”和”aeiou”,則刪除之后的第一個字符串變成”Thy r stdnts.”。
思路:不可避免的是遍歷第一個字符串,如果遍歷一個字符,都需要去第二個字符串中查找其存不存在,那么復雜度會是O(nm),當然由於字符數有限,所以m是個常量。關於查找速度最快的當然是hash表,對於8位字符,size=2^8足矣。
關於刪除字符,后面的字符要往前移,如果每刪除一個就移一次,O(n^2)這復雜度實在太高,僅僅用快慢指針就可以搞定,這個方法非常有用,比如求解循環鏈表。
初始化:快慢指針指向第一個字符
循環:如果快指針指的是不需要的字符,將值賦給慢指針后,快慢指針同時++;如果快指針指向待刪除字符,那么直接++;
終止:快指針指向'\0'
- /*
- * Copyright (c) 2011 alexingcool. All Rights Reserved.
- */
- #include <iostream>
- #define NUMBER 256
- using namespace std;
- char firstArray[] = "They are students.";
- char secondArray[] = "aeiou";
- const int firstSize = sizeof firstArray / sizeof *firstArray;
- const int secondSize = sizeof secondArray / sizeof *secondArray;
- bool flag[NUMBER];
- void deleteArray(char *firstArray, char *secondArray)
- {
- if(firstArray == NULL || secondArray == NULL)
- return;
- for(int i = 0; i < NUMBER; i++) {
- flag[i] = false;
- }
- for(int i = 0; i < secondSize; i++) {
- int pos = static_cast<int>(secondArray[i]);
- flag[pos] = true;
- }
- char *fast = firstArray, *slow = firstArray;
- while(*fast != '\0') {
- if(flag[*fast] == false) {
- *slow = *fast;
- slow++;
- }
- fast++;
- }
- *slow = 0;
- }
- void main()
- {
- deleteArray(firstArray, secondArray);
- cout << firstArray << endl;
- }
結果如下: