In the world of computers, string problems can be said to be a very important problem, such as text processing and so on. Today Mayuyu is going to tell you about a string deletion problem, which is described below.
problem: given a very long string, such as length 1000000, now to delete some of the specified characters in this string, the specified characters are only
there are several , now Mayuyu is asking for the least amount of time and space to do it.
Analysis: It is obvious that you can scan from the go, encounter a specified character on the delete, and then move the back forward. Obviously, it's time complexity.
Too big, so it is necessary to design a better algorithm. In fact, this can be considered, we can use two pointers in front of the previous scan, encountered the need
To delete the following string to overwrite the previous, so that the time complexity is O (n), and do not need to open additional space. As for how
To find out if the specified character exists, you need to pre-preprocess it with an array first.
Code:
#include <iostream> #include <string.h> #include <stdio.h>using namespace Std;int flag[123]; Uppercase and lowercase ASCII values up to 122void Init (const char *str) {memset (flag, 0, sizeof (flag)), while (*STR) flag[*str++] = 1;} void Delete (char *str) {char *pfast = Str;char *pslow = Str;while (*pfast) {if (!flag[*pfast]) *pslow++ = *pfast++;elsepfast+ +;} *pslow = 0;} int main () {char source[] = "Hello Mayuyu!!!"; Char word[] = "Hello"; Init (word);D elete (source); cout << source << Endl;return 0;}
String deletion issues