String deletion issues

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.