Revert words in a sentence, so " The quick brown fox jumped over the lazy dog." becomes "dog. lazy the over jumped fox brown quick The" .
In C:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
void revertWord( char *start, char *end ) { | |
char temp; | |
while( start < end ) { | |
temp = *start; | |
*start = *end; | |
*end = temp; | |
++start; | |
--end; | |
} | |
} | |
void revertString(char *sentence) { | |
char *start = sentence; | |
char *end = sentence; | |
while ( *(++end) ); // to the null | |
// but don't touch not null | |
--end; | |
// all sentence first | |
revertWord( start, end ); | |
// and now word by word | |
while ( *start ) { // not null? | |
// find space if any, move start to it | |
for (; *start && *start == ' '; ++start ); | |
// find end fo the word, move end to it | |
for ( end = start; *end && *end != ' '; ++end ); | |
// space or null, back one | |
--end; | |
// reverse from start to end | |
revertWord( start, end ); | |
// next word or null | |
start = ++end; | |
} | |
} | |
int main() { | |
char test[] = "The quick brown fox jumped over the lazy dog."; | |
printf( "before: %s\n", test ); | |
revertString(test); | |
printf( "after: %s\n", test ); | |
return 0; | |
} |
In C++:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sstream> | |
#include <stack> | |
using namespace std; | |
// using stack | |
string revertStack( string sentence ) { | |
stringstream inout(sentence); | |
string word, news; | |
stack<string> st; | |
while ( inout >> word ) { | |
st.push( word ); | |
} | |
while ( st.size() ) { | |
news += " " + st.top(); | |
st.pop(); | |
} | |
return news; | |
} | |
int main() { | |
string sentence = "The quick brown fox jumped over the lazy dog."; | |
sentence = revertStack( sentence ); | |
cout << sentence << endl; | |
} |
In py:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sentence = "The quick brown fox jumped over the lazy dog." | |
print "before: ", sentence | |
sentence = " ".join( sentence.split()[::-1] ) | |
print "after: ", sentence |
52 > 27 > 4!
Brak komentarzy:
Prześlij komentarz