Preface:
From today onwards, this programmer began to focus on writing his own blog. Before, I collected a lot of good articles, whether from cnblog above or csdn above. I have benefited greatly from it. I think the knowledge belongs to everyone, I should also contribute my own ideas. So start with the simplest algorithm first.
I'm going to start with the string algorithm because string processing is something we often encounter in programming, such as substring, reverse string, and so on. All right, no more talking nonsense. Let's get started.
Text:
Today's algorithm is to flip a string. The topics are as follows:
"title" Enter an English sentence, flipping the order of the words in the sentence, but the order of the characters within the word does not change. Words are separated by spaces in sentences. "Example" input "I am a student.", then output "student." A am I ".
"Analysis" for an English sentence, everyone knows that it is separated by a space. So how to flip the English sentence and keep the word order in the same. Of course we can open up a new space and then scan the source string from behind, encounter a space stop, and copy the substring into the target space. This is our intuitive thinking. Then it is necessary to open up a new space, and the space efficiency should be O (n).
So we're thinking, first we flip the whole string, and then we flip the substrings again (the substrings are separated by a space). Would that be the end of the way? Take the example above. After the entire string is flipped we get ". Tneduts a ma I" and then flip the substring, we get "student." A am I ". That's the result we got. The code is as follows:
#include <iostream>
#include <cstring>
void Word_reverse (char * const word, int start, int end)
{
char ch;
while (Start < end)
{
ch = word[start];
Word[start] = Word[end];
Word[end] = ch;
start++;
end--;
}
}
char * SETENCE_REVERSE (char * const setence, int length)
{
int end = 0;
Word_reverse (setence, 0, length-1);
for (int start = 0, start < length; start + = end + 1)
{for
(end = start; end < length && setence [end]! = '; end++);
Word_reverse (setence, start, end-1);
}
return setence;
}
int main (int argc, char * * argv)
{
char data[] = "I am a students.";
char * PResult = setence_reverse (data, strlen (data));
Std::cout << pResult << Std::endl;
return 0;
}
Conclusion:
We enter I am a students. The output is as follows: