Given an input string, reverse the string word by word.
For example,
Given s = " the sky is blue
",
Return " blue is sky the
".
Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between and words?
Reduce them to a single space in the reversed string.
There are simple ways to use Java or Python:
This is my first AC code, with the Split () method:
Public string Reversewords (string s) { = S.split (""); = ""; for (int i=token.length;i>0;i--) { if(Token[i-1].compareto (")!=0) = re + token[i-1] +" "; } return Re.trim (); }
Later see discuss said is cheat, change to:
Publicstring Reversewords (string s) {ArrayList<String> ls =NewArraylist<string>(); intI=0; while(i<s.length ()) { if(! (S.charat (i) = = ")) { intj=i; String Temp= ""; while(J<s.length () &&! (S.charat (j) = = ") ) {temp+=S.charat (j); J++; } ls.add (temp); I=J; } ElseI++; } String re= ""; for(intJ=ls.size () -1;j>=0;j--) {Re= re + ls.get (j) + ""; } returnRe.equals ("")? Re:re.substring (0,re.length ()-1); }
Scan down with non-whitespace until you encounter a space or scan to the end of the string to get a complete word.
Take a data structure (here with ArrayList) to save the intercepted word and then output it from the back.
Finally, you need to remove the possible trailing spaces.
[Leetcode] [JAVA] Reverse Words in a String