Example: Input: "前开发者教程 is a good website", Output: " website good a is 前开发者教程".
解决方法如下:
步骤1:颠倒整个字符串。
步骤2:颠倒字符串中的单个单词。
除了上述两个步骤,我们还需要删除前导和尾随空格以及单词之间的多余空格。
C ++解决方案
#include<iostream> #include<string.h> #include<algorithm> using namespace std; void reverseWords(string &str) { int start = 0; int i = 0; cout<<"\n\n============debugging logs start==========="; //remove leading space while( str[i] == ' ') str.erase(i, 1); cout<<"\nStep 1 after removing leading space = "<<str<<endl; //reverse words reverse(str.begin(), str.end()); cout<<"Step 2 after reversing the words = "<<str<<endl; //remove trailing zeros while( str[i] == ' ') str.erase(i, 1); cout<<"Step 3 after trailing zeros= "<<str<<endl; int size = str.size(); for(i = 0; i < size - 1; i++) { //check if you encounter a space. // if you encounter a space, then it is a word, reverse the word. if( str[i] == ' ') { if( i == start ) { // if there is more than 上 e space between two words, remove extra space str.erase(i--,1); size--; cout<<"Step 4 removing extra space between words = "<<str<<endl; } else { // reverse word. reverse(str.begin()+start, str.begin()+i); start = i+1; cout<<"Step 5 reversing single word = "<<str<<endl; } } } // reverse the last word. reverse(str.begin() + start, str.end()); cout<<"Step 6 reversing last word = "<<str<<endl; cout<<"============debugging logs end===========\n\n"<<endl; } int main() { string str = " Hello world from 前开发者教程.com "; cout<<"\nOriginal string = "<<endl; cout<<"\""<< str <<"\""; reverseWords(str); cout<<"String after reversing words = "<<endl; cout<<str<<endl; return 0; }
输出:
Original string = " Hello world from 前开发者教程.com " ============debugging logs start=========== Step 1 after removing leading space = Hello world from 前开发者教程.com Step 2 after reversing the words = moc.lairotutrepolevedorp morf dlrow olleH Step 3 after trailing zeros= moc.lairotutrepolevedorp morf dlrow olleH Step 5 reversing single word = 前开发者教程.com morf dlrow olleH Step 4 removing extra space between words = 前开发者教程.com morf dlrow olleH Step 4 removing extra space between words = 前开发者教程.com morf dlrow olleH Step 4 removing extra space between words = 前开发者教程.com morf dlrow olleH Step 5 reversing single word = 前开发者教程.com from dlrow olleH Step 4 removing extra space between words = 前开发者教程.com from dlrow olleH Step 4 removing extra space between words = 前开发者教程.com from dlrow olleH Step 5 reversing single word = 前开发者教程.com from world olleH Step 4 removing extra space between words = 前开发者教程.com from world olleH Step 4 removing extra space between words = 前开发者教程.com from world olleH Step 4 removing extra space between words = 前开发者教程.com from world olleH Step 6 reversing last word = 前开发者教程.com from world Hello ============debugging logs end=========== String after reversing words = prodevelopertutorial.com from world Hello
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |