One problem is how to delete two characters with the same string, such
Str1 = "abcdeafg" str2 = "blimklaaaaa"
To get:
Str1 = "cdefg" str2 = "limkl"
Write the program directly below. I wrote this program, but the idea is others '.
For the convenience of discussion, assume that both str1 and str2 are ASCII codes.
- Void delsamechs (char * str1, char * str2)
- {
- // The ASCII code is 0-255 (accurate to 0-127). Therefore, a temporary array is defined and its subscript is ASCII code.
- // Its element is the number of times that subscript I appears in str1 and str2
- Int temp [256];
- Char * pstr1 = str1;
- Char * pstr2 = str2;
- Memset (& temp, 0, sizeof (temp); // clear 0
- While ('/0 '! = * Pstr1) // traverse str1 and set it to 1 in temp
- {
- Temp [* pstr1] = 1;
- Pstr1 ++;
- }
- While ('/0 '! = * Pstr2) // traverse str2. If it is 1, set it to 2 in temp. If it is 2, it is the public element of the two strings.
- {
- If (1 = temp [* pstr2])
- Temp [* pstr2] = 2;
- Pstr2 ++;
- }
- For (INT I = 0; I <256; I ++)
- {
- If (2 = temp [I])
- {
- Delch (str1, I); // delete all character I in str1 (if any)
- Delch (str2, I );
- }
- }
- }
The principle of doing so is to change the space for time and sacrifice the space of 256 integers (which can be replaced by char temp [256 ), A three-time Parallel loop can be used to find the same elements of the two arrays. If the conventional method is used, it is estimated that the nested loop should be 3 times ~
If it is Unicode, you can set int temp [65536];
If it is multi-byte encoding, I have never thought about it ~
The following describes the implementation of void delchar (char * STR, char ch.
Because it is necessary to delete all the I, if it is a general practice, each time you delete an element, the following will move to the front, it will take a lot of time.
Next, let's look at this Code:
- Void delchar (char * STR, char ch)
- {
- Char * pcurr = STR; // used to process the deleted result
- Char * ptemp = STR; // used to scan the source string Str
- While ('/0 '! = * Ptemp)
- {
- If (Ch! = * Ptemp)
- {
- * Pcurr = * ptemp;
- Pcurr ++;
- }
- Ptemp ++;
- }
- * Pcurr = '/0 ';
- }
The idea of this Code is different from that of the conventional code. If you move the code in the past, you don't want to delete it. Instead, you don't want to move it. In this way, you only need to scan once.
In this way, the entire program can complete the task by scanning up to five strings.
It can also be extended. If you delete multiple strings with the same characters, all of them are processed in this way, and the complexity is O (n)
Can it be simplified ??? I cannot think of it now. Please give me more advice. Thank you very much.
Note: The idea of this delchar program is obtained by referring to the unique source code in STL algorithm.