This problem is a lot of string boundary problems, involving spaces, reversal problems. Very troublesome, remember previously only did the similar question, should have the simple method, but did not find, later looked again.
//for a given string, we need to deform it in a linear (that is, O (n)) time. First, the string contains a few spaces,//just like "Hello world", what we're going to do is reverse the words in a string separated by spaces, and reverse the case of each character. //For example, "Hello World" is transformed into "World Hello". //Input Description://given a string s and its length n (1≤n≤500)////Output Description://please return the deformed string. The title guarantees that the given string is composed of uppercase and lowercase letters and spaces. ////Input Example://"This is a sample",////Output Example://"SAMPLE A is this"////This problem does not look very difficult, but many border problems need to be considered. //For example: # #this #is#a#sample## returns # #SAMPLE #a#is#this## instead of Sample#a#is#this. (Tips: #代表空格)//the idea of the subject: first replace the string case, then invert the entire string, and finally reverse each word, the other does not change. #include <iostream>using namespacestd; #include<string>#include<stack>#include<vector>classTransform { Public: stringTransstringSintN) {//Write code herevector<Char>VEC; Stack<vector<Char> >STA; for(inti =0; I < n;i++) { if('Z'>=s[i]&&s[i]>='A') {S[i]= S[i] + +; Vec.push_back (S[i]); if(i = = (N-1))//finally no end sign{Sta.push (VEC); Vec.clear (); } } Else if('a'<=s[i]&&'Z'>=S[i]) {S[i]= S[i]- +; Vec.push_back (S[i]); if(i== (n1) {Sta.push (VEC); Vec.clear (); } } Else if(s[i]==' ') { if(!vec.empty ())//the case of a space{Sta.push (VEC); Vec.clear (); } vec.push_back (S[i]); Sta.push (VEC); Vec.clear (); } } stringresult; while(!Sta.empty ()) {Vector<Char> temp=Sta.top (); for(Auto it = Temp.begin (); it!= temp.end (); it++) {result+= *it; } //result + = ";Sta.pop (); } returnresult; }};intMain () {Transform T; stringstr; intN; Getline (CIN,STR); CIN>>N; //T.trans (str,n);cout << T.trans (str, n) <<Endl;}//reverse and case changes can be made separately. classTransform { Public: stringTransstringSintN) {//Write code here//case -sensitive replacement for(inti =0; I < n; i++){ if(S[i] >='a'&&s[i] <='Z') {S[i]=ToUpper (S[i]); } Else if(S[i] >='A'&&s[i] <='Z') {S[i]=ToLower (S[i]); } } //Invert entire stringReverse (S.begin (), S.end ()); Auto Pbegin=S.begin (); Auto Pend=S.begin (); while(*pend! =' /'){ if(*pend = =' '){ //The word is reversed when it touches a spacereverse (Pbegin, pend); Pbegin= Pend +1; } ++Pend; } //handle boundary conditions, the word at the end of the string needs to be reversedreverse (Pbegin, pend); returns; }};
Deformation of a string